diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..9fdea984c6a1d5c27896f73bc5941ae8059f8e0f --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,57 @@ +stages: + - test + - build_app + - scan + - deploy_app_testing + + +variables: + IMAGE_NAME: ${CI_REGISTRY_IMAGE}/app:latest + +build_app: + stage: build_app + image: docker:stable + variables: + DOCKER_DRIVER: overlay2 + services: + - docker:dind + before_script: + - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY + script: + - docker build --cache-from $CI_REGISTRY/wimma-lab-2019/mysticons/cayac/demofrontend/app:latest --tag $CI_REGISTRY/wimma-lab-201$ + - docker push $CI_REGISTRY/wimma-lab-2019/mysticons/cayac/demofrontend/app:latest + only: + - Development + + +container_scan_service: + stage: scan + variables: + ANCHORE_CLI_URL: "http://anchore-engine:8228/v1" + GIT_STRATEGY: none + image: docker.io/anchore/inline-scan:v0.3.3 + services: + - name: docker.io/anchore/inline-scan:v0.3.3 + alias: anchore-engine + command: ["start"] + - name: anchore/engine-db-preload:v0.3.3 + alias: anchore-db + + +script: +- anchore-cli system wait +- anchore-cli registry add "$CI_REGISTRY" gitlab-ci-token "$CI_JOB_TOKEN" --skip-validate +- anchore_ci_tools.py -a -r --timeout 500 --image $IMAGE_NAME + +artifacts: + name: ${CI_JOB_NAME}-${CI_COMMIT_REF_NAME} + paths: + - anchore-reports/* +only: + - Development + + + + + + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cbd5be4ef3efe3d5ce7aaa2bc38f7b9ab7899996 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM node:12.2.0-alpine + +# Create app directory +WORKDIR /usr/src/app + +# Install app dependencies +# A wildcard is used to ensure both package.json AND package-lock.json are copied +# where available (npm@5+) +COPY package*.json ./ + +RUN npm install +RUN npm install --silent +# If you are building your code for production +# RUN npm ci --only=production + +# Bundle app source +COPY . . + +# default values +ENV REACT_APP_API_ROOT=http://localhost:8080/api +# expose to 4100 port + +EXPOSE 4100 +CMD [ "npm", "start" ] + diff --git a/README.md b/README.md index ede1c604561b44b87f5f0b5f90d0fc4180af7320..776ea0a6038364a08c92913053b53b2689961f7f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,74 @@ -# source-demo-front +#  +[](http://realworld.io) + +> ### React + Redux codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the [RealWorld](https://github.com/gothinkster/realworld-example-apps) spec and API. + +<a href="https://stackblitz.com/edit/react-redux-realworld" target="_blank"><img width="187" src="https://github.com/gothinkster/realworld/blob/master/media/edit_on_blitz.png?raw=true" /></a> <a href="https://thinkster.io/tutorials/build-a-real-world-react-redux-application" target="_blank"><img width="384" src="https://raw.githubusercontent.com/gothinkster/realworld/master/media/learn-btn-hr.png" /></a> + +### [Demo](https://react-redux.realworld.io) [RealWorld](https://github.com/gothinkster/realworld) + +Originally created for this [GH issue](https://github.com/reactjs/redux/issues/1353). The codebase is now feature complete; please submit bug fixes via pull requests & feedback via issues. + +We also have notes in [**our wiki**](https://github.com/gothinkster/react-redux-realworld-example-app/wiki) about how the various patterns used in this codebase and how they work (thanks [@thejmazz](https://github.com/thejmazz)!) + + +## Getting started + +You can view a live demo over at https://react-redux.realworld.io/ + +To get the frontend running locally: + +- Clone this repo +- `npm install` to install all req'd dependencies +- `npm start` to start the local server (this project uses create-react-app) + +Local web server will use port 4100 instead of standard React's port 3000 to prevent conflicts with some backends like Node or Rails. You can configure port in scripts section of `package.json`: we use [cross-env](https://github.com/kentcdodds/cross-env) to set environment variable PORT for React scripts, this is Windows-compatible way of setting environment variables. + +Alternatively, you can add `.env` file in the root folder of project to set environment variables (use PORT to change webserver's port). This file will be ignored by git, so it is suitable for API keys and other sensitive stuff. Refer to [dotenv](https://github.com/motdotla/dotenv) and [React](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-development-environment-variables-in-env) documentation for more details. Also, please remove setting variable via script section of `package.json` - `dotenv` never override variables if they are already set. + +### Making requests to the backend API + +For convenience, we have a live API server running at https://conduit.productionready.io/api for the application to make requests against. You can view [the API spec here](https://github.com/GoThinkster/productionready/blob/master/api) which contains all routes & responses for the server. + +The source code for the backend server (available for Node, Rails and Django) can be found in the [main RealWorld repo](https://github.com/gothinkster/realworld). + +If you want to change the API URL to a local server, simply edit `src/agent.js` and change `API_ROOT` to the local server's URL (i.e. `http://localhost:3000/api`) + + +## Functionality overview + +The example application is a social blogging site (i.e. a Medium.com clone) called "Conduit". It uses a custom API for all requests, including authentication. You can view a live demo over at https://redux.productionready.io/ + +**General functionality:** + +- Authenticate users via JWT (login/signup pages + logout button on settings page) +- CRU* users (sign up & settings page - no deleting required) +- CRUD Articles +- CR*D Comments on articles (no updating required) +- GET and display paginated lists of articles +- Favorite articles +- Follow other users + +**The general page breakdown looks like this:** + +- Home page (URL: /#/ ) + - List of tags + - List of articles pulled from either Feed, Global, or by Tag + - Pagination for list of articles +- Sign in/Sign up pages (URL: /#/login, /#/register ) + - Use JWT (store the token in localStorage) +- Settings page (URL: /#/settings ) +- Editor page to create/edit articles (URL: /#/editor, /#/editor/article-slug-here ) +- Article page (URL: /#/article/article-slug-here ) + - Delete article button (only shown to article's author) + - Render markdown from server client side + - Comments section at bottom of page + - Delete comment button (only shown to comment's author) +- Profile page (URL: /#/@username, /#/@username/favorites ) + - Show basic user info + - List of articles populated from author's created articles or author's favorited articles + +<br /> + +[](https://thinkster.io) diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9680bc6c66408f0a7fb955cdfb9af341777b069f --- /dev/null +++ b/package.json @@ -0,0 +1,31 @@ +{ + "name": "react-redux-realworld-example-app", + "version": "0.1.0", + "private": true, + "devDependencies": { + "cross-env": "^5.1.4", + "react-scripts": "1.1.1" + }, + "dependencies": { + "history": "^4.6.3", + "marked": "^0.3.6", + "prop-types": "^15.5.10", + "react": "^16.3.0", + "react-dom": "^16.3.0", + "react-redux": "^5.0.7", + "react-router": "^4.1.2", + "react-router-dom": "^4.1.2", + "react-router-redux": "^5.0.0-alpha.6", + "redux": "^3.6.0", + "redux-devtools-extension": "^2.13.2", + "redux-logger": "^3.0.1", + "superagent": "^3.8.2", + "superagent-promise": "^1.1.0" + }, + "scripts": { + "start": "cross-env PORT=4100 react-scripts start", + "build": "react-scripts build", + "test": "cross-env PORT=4100 react-scripts test --env=jsdom", + "eject": "react-scripts eject" + } +} diff --git a/project-logo.png b/project-logo.png new file mode 100644 index 0000000000000000000000000000000000000000..901b3b61b38fe94e2ded8be5632eb358be039cbc Binary files /dev/null and b/project-logo.png differ diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..5c125de5d897c1ff5692a656485b3216123dcd89 Binary files /dev/null and b/public/favicon.ico differ diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7253c80675b581635fa72d16eda74ff6e121add2 --- /dev/null +++ b/public/index.html @@ -0,0 +1,34 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> + <link rel="stylesheet" href="//demo.productionready.io/main.css"> + <link href="//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css"> + <link href="//fonts.googleapis.com/css?family=Titillium+Web:700|Source+Serif+Pro:400,700|Merriweather+Sans:400,700|Source+Sans+Pro:400,300,600,700,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css"> + <!-- + Notice the use of %PUBLIC_URL% in the tag above. + It will be replaced with the URL of the `public` folder during the build. + Only files inside the `public` folder can be referenced from the HTML. + + Unlike "/favicon.ico" or "favico.ico", "%PUBLIC_URL%/favicon.ico" will + work correctly both with client-side routing and a non-root public URL. + Learn how to configure a non-root public URL by running `npm run build`. + --> + <title>Conduit</title> + </head> + <body> + <div id="root"></div> + <!-- + This HTML file is a template. + If you open it directly in the browser, you will see an empty page. + + You can add webfonts, meta tags, or analytics to this file. + The build step will place the bundled scripts into the <body> tag. + + To begin the development, run `npm start`. + To create a production bundle, use `npm run build`. + --> + </body> +</html> diff --git a/src/agent.js b/src/agent.js new file mode 100644 index 0000000000000000000000000000000000000000..adfbd7254fcba5990871391ab3b7025a211280a7 --- /dev/null +++ b/src/agent.js @@ -0,0 +1,96 @@ +import superagentPromise from 'superagent-promise'; +import _superagent from 'superagent'; + +const superagent = superagentPromise(_superagent, global.Promise); + +const API_ROOT = 'https://conduit.productionready.io/api'; + +const encode = encodeURIComponent; +const responseBody = res => res.body; + +let token = null; +const tokenPlugin = req => { + if (token) { + req.set('authorization', `Token ${token}`); + } +} + +const requests = { + del: url => + superagent.del(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody), + get: url => + superagent.get(`${API_ROOT}${url}`).use(tokenPlugin).then(responseBody), + put: (url, body) => + superagent.put(`${API_ROOT}${url}`, body).use(tokenPlugin).then(responseBody), + post: (url, body) => + superagent.post(`${API_ROOT}${url}`, body).use(tokenPlugin).then(responseBody) +}; + +const Auth = { + current: () => + requests.get('/user'), + login: (email, password) => + requests.post('/users/login', { user: { email, password } }), + register: (username, email, password) => + requests.post('/users', { user: { username, email, password } }), + save: user => + requests.put('/user', { user }) +}; + +const Tags = { + getAll: () => requests.get('/tags') +}; + +const limit = (count, p) => `limit=${count}&offset=${p ? p * count : 0}`; +const omitSlug = article => Object.assign({}, article, { slug: undefined }) +const Articles = { + all: page => + requests.get(`/articles?${limit(10, page)}`), + byAuthor: (author, page) => + requests.get(`/articles?author=${encode(author)}&${limit(5, page)}`), + byTag: (tag, page) => + requests.get(`/articles?tag=${encode(tag)}&${limit(10, page)}`), + del: slug => + requests.del(`/articles/${slug}`), + favorite: slug => + requests.post(`/articles/${slug}/favorite`), + favoritedBy: (author, page) => + requests.get(`/articles?favorited=${encode(author)}&${limit(5, page)}`), + feed: () => + requests.get('/articles/feed?limit=10&offset=0'), + get: slug => + requests.get(`/articles/${slug}`), + unfavorite: slug => + requests.del(`/articles/${slug}/favorite`), + update: article => + requests.put(`/articles/${article.slug}`, { article: omitSlug(article) }), + create: article => + requests.post('/articles', { article }) +}; + +const Comments = { + create: (slug, comment) => + requests.post(`/articles/${slug}/comments`, { comment }), + delete: (slug, commentId) => + requests.del(`/articles/${slug}/comments/${commentId}`), + forArticle: slug => + requests.get(`/articles/${slug}/comments`) +}; + +const Profile = { + follow: username => + requests.post(`/profiles/${username}/follow`), + get: username => + requests.get(`/profiles/${username}`), + unfollow: username => + requests.del(`/profiles/${username}/follow`) +}; + +export default { + Articles, + Auth, + Comments, + Profile, + Tags, + setToken: _token => { token = _token; } +}; diff --git a/src/components/App.js b/src/components/App.js new file mode 100644 index 0000000000000000000000000000000000000000..980ea72bb4f15a5104a845b6b9cdf03ade4fca9b --- /dev/null +++ b/src/components/App.js @@ -0,0 +1,86 @@ +import agent from '../agent'; +import Header from './Header'; +import React from 'react'; +import { connect } from 'react-redux'; +import { APP_LOAD, REDIRECT } from '../constants/actionTypes'; +import { Route, Switch } from 'react-router-dom'; +import Article from '../components/Article'; +import Editor from '../components/Editor'; +import Home from '../components/Home'; +import Login from '../components/Login'; +import Profile from '../components/Profile'; +import ProfileFavorites from '../components/ProfileFavorites'; +import Register from '../components/Register'; +import Settings from '../components/Settings'; +import { store } from '../store'; +import { push } from 'react-router-redux'; + +const mapStateToProps = state => { + return { + appLoaded: state.common.appLoaded, + appName: state.common.appName, + currentUser: state.common.currentUser, + redirectTo: state.common.redirectTo + }}; + +const mapDispatchToProps = dispatch => ({ + onLoad: (payload, token) => + dispatch({ type: APP_LOAD, payload, token, skipTracking: true }), + onRedirect: () => + dispatch({ type: REDIRECT }) +}); + +class App extends React.Component { + componentWillReceiveProps(nextProps) { + if (nextProps.redirectTo) { + // this.context.router.replace(nextProps.redirectTo); + store.dispatch(push(nextProps.redirectTo)); + this.props.onRedirect(); + } + } + + componentWillMount() { + const token = window.localStorage.getItem('jwt'); + if (token) { + agent.setToken(token); + } + + this.props.onLoad(token ? agent.Auth.current() : null, token); + } + + render() { + if (this.props.appLoaded) { + return ( + <div> + <Header + appName={this.props.appName} + currentUser={this.props.currentUser} /> + <Switch> + <Route exact path="/" component={Home}/> + <Route path="/login" component={Login} /> + <Route path="/register" component={Register} /> + <Route path="/editor/:slug" component={Editor} /> + <Route path="/editor" component={Editor} /> + <Route path="/article/:id" component={Article} /> + <Route path="/settings" component={Settings} /> + <Route path="/@:username/favorites" component={ProfileFavorites} /> + <Route path="/@:username" component={Profile} /> + </Switch> + </div> + ); + } + return ( + <div> + <Header + appName={this.props.appName} + currentUser={this.props.currentUser} /> + </div> + ); + } +} + +// App.contextTypes = { +// router: PropTypes.object.isRequired +// }; + +export default connect(mapStateToProps, mapDispatchToProps)(App); diff --git a/src/components/Article/ArticleActions.js b/src/components/Article/ArticleActions.js new file mode 100644 index 0000000000000000000000000000000000000000..032e77da7b13d49c8a3960837f955b5a372e4b69 --- /dev/null +++ b/src/components/Article/ArticleActions.js @@ -0,0 +1,41 @@ +import { Link } from 'react-router-dom'; +import React from 'react'; +import agent from '../../agent'; +import { connect } from 'react-redux'; +import { DELETE_ARTICLE } from '../../constants/actionTypes'; + +const mapDispatchToProps = dispatch => ({ + onClickDelete: payload => + dispatch({ type: DELETE_ARTICLE, payload }) +}); + +const ArticleActions = props => { + const article = props.article; + const del = () => { + props.onClickDelete(agent.Articles.del(article.slug)) + }; + if (props.canModify) { + return ( + <span> + + <Link + to={`/editor/${article.slug}`} + className="btn btn-outline-secondary btn-sm"> + <i className="ion-edit"></i> Edit Article + </Link> + + <button className="btn btn-outline-danger btn-sm" onClick={del}> + <i className="ion-trash-a"></i> Delete Article + </button> + + </span> + ); + } + + return ( + <span> + </span> + ); +}; + +export default connect(() => ({}), mapDispatchToProps)(ArticleActions); diff --git a/src/components/Article/ArticleMeta.js b/src/components/Article/ArticleMeta.js new file mode 100644 index 0000000000000000000000000000000000000000..a30b35aee8d30dbed52b3ba5cecd1e3c1965a909 --- /dev/null +++ b/src/components/Article/ArticleMeta.js @@ -0,0 +1,27 @@ +import ArticleActions from './ArticleActions'; +import { Link } from 'react-router-dom'; +import React from 'react'; + +const ArticleMeta = props => { + const article = props.article; + return ( + <div className="article-meta"> + <Link to={`/@${article.author.username}`}> + <img src={article.author.image} alt={article.author.username} /> + </Link> + + <div className="info"> + <Link to={`/@${article.author.username}`} className="author"> + {article.author.username} + </Link> + <span className="date"> + {new Date(article.createdAt).toDateString()} + </span> + </div> + + <ArticleActions canModify={props.canModify} article={article} /> + </div> + ); +}; + +export default ArticleMeta; diff --git a/src/components/Article/Comment.js b/src/components/Article/Comment.js new file mode 100644 index 0000000000000000000000000000000000000000..adb34a7c2b204347369dd72c48b469a14dc1c1d0 --- /dev/null +++ b/src/components/Article/Comment.js @@ -0,0 +1,35 @@ +import DeleteButton from './DeleteButton'; +import { Link } from 'react-router-dom'; +import React from 'react'; + +const Comment = props => { + const comment = props.comment; + const show = props.currentUser && + props.currentUser.username === comment.author.username; + return ( + <div className="card"> + <div className="card-block"> + <p className="card-text">{comment.body}</p> + </div> + <div className="card-footer"> + <Link + to={`/@${comment.author.username}`} + className="comment-author"> + <img src={comment.author.image} className="comment-author-img" alt={comment.author.username} /> + </Link> + + <Link + to={`/@${comment.author.username}`} + className="comment-author"> + {comment.author.username} + </Link> + <span className="date-posted"> + {new Date(comment.createdAt).toDateString()} + </span> + <DeleteButton show={show} slug={props.slug} commentId={comment.id} /> + </div> + </div> + ); +}; + +export default Comment; diff --git a/src/components/Article/CommentContainer.js b/src/components/Article/CommentContainer.js new file mode 100644 index 0000000000000000000000000000000000000000..625194ecdf4b0857b83201bdba1845015217d997 --- /dev/null +++ b/src/components/Article/CommentContainer.js @@ -0,0 +1,40 @@ +import CommentInput from './CommentInput'; +import CommentList from './CommentList'; +import { Link } from 'react-router-dom'; +import React from 'react'; + +const CommentContainer = props => { + if (props.currentUser) { + return ( + <div className="col-xs-12 col-md-8 offset-md-2"> + <div> + <list-errors errors={props.errors}></list-errors> + <CommentInput slug={props.slug} currentUser={props.currentUser} /> + </div> + + <CommentList + comments={props.comments} + slug={props.slug} + currentUser={props.currentUser} /> + </div> + ); + } else { + return ( + <div className="col-xs-12 col-md-8 offset-md-2"> + <p> + <Link to="/login">Sign in</Link> + or + <Link to="/register">sign up</Link> + to add comments on this article. + </p> + + <CommentList + comments={props.comments} + slug={props.slug} + currentUser={props.currentUser} /> + </div> + ); + } +}; + +export default CommentContainer; diff --git a/src/components/Article/CommentInput.js b/src/components/Article/CommentInput.js new file mode 100644 index 0000000000000000000000000000000000000000..3007ab99a3fb7b869a3f28ed59e056cc2a2fab8c --- /dev/null +++ b/src/components/Article/CommentInput.js @@ -0,0 +1,58 @@ +import React from 'react'; +import agent from '../../agent'; +import { connect } from 'react-redux'; +import { ADD_COMMENT } from '../../constants/actionTypes'; + +const mapDispatchToProps = dispatch => ({ + onSubmit: payload => + dispatch({ type: ADD_COMMENT, payload }) +}); + +class CommentInput extends React.Component { + constructor() { + super(); + this.state = { + body: '' + }; + + this.setBody = ev => { + this.setState({ body: ev.target.value }); + }; + + this.createComment = ev => { + ev.preventDefault(); + const payload = agent.Comments.create(this.props.slug, + { body: this.state.body }); + this.setState({ body: '' }); + this.props.onSubmit(payload); + }; + } + + render() { + return ( + <form className="card comment-form" onSubmit={this.createComment}> + <div className="card-block"> + <textarea className="form-control" + placeholder="Write a comment..." + value={this.state.body} + onChange={this.setBody} + rows="3"> + </textarea> + </div> + <div className="card-footer"> + <img + src={this.props.currentUser.image} + className="comment-author-img" + alt={this.props.currentUser.username} /> + <button + className="btn btn-sm btn-primary" + type="submit"> + Post Comment + </button> + </div> + </form> + ); + } +} + +export default connect(() => ({}), mapDispatchToProps)(CommentInput); diff --git a/src/components/Article/CommentList.js b/src/components/Article/CommentList.js new file mode 100644 index 0000000000000000000000000000000000000000..b62889de8460880583f7da64d5579be4c03f4111 --- /dev/null +++ b/src/components/Article/CommentList.js @@ -0,0 +1,22 @@ +import Comment from './Comment'; +import React from 'react'; + +const CommentList = props => { + return ( + <div> + { + props.comments.map(comment => { + return ( + <Comment + comment={comment} + currentUser={props.currentUser} + slug={props.slug} + key={comment.id} /> + ); + }) + } + </div> + ); +}; + +export default CommentList; diff --git a/src/components/Article/DeleteButton.js b/src/components/Article/DeleteButton.js new file mode 100644 index 0000000000000000000000000000000000000000..b07d65719a4ba65f3081d3d75142d455e19dca1e --- /dev/null +++ b/src/components/Article/DeleteButton.js @@ -0,0 +1,27 @@ +import React from 'react'; +import agent from '../../agent'; +import { connect } from 'react-redux'; +import { DELETE_COMMENT } from '../../constants/actionTypes'; + +const mapDispatchToProps = dispatch => ({ + onClick: (payload, commentId) => + dispatch({ type: DELETE_COMMENT, payload, commentId }) +}); + +const DeleteButton = props => { + const del = () => { + const payload = agent.Comments.delete(props.slug, props.commentId); + props.onClick(payload, props.commentId); + }; + + if (props.show) { + return ( + <span className="mod-options"> + <i className="ion-trash-a" onClick={del}></i> + </span> + ); + } + return null; +}; + +export default connect(() => ({}), mapDispatchToProps)(DeleteButton); diff --git a/src/components/Article/index.js b/src/components/Article/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6be8975f62940155903dae13b0ccfb28058f326d --- /dev/null +++ b/src/components/Article/index.js @@ -0,0 +1,97 @@ +import ArticleMeta from './ArticleMeta'; +import CommentContainer from './CommentContainer'; +import React from 'react'; +import agent from '../../agent'; +import { connect } from 'react-redux'; +import marked from 'marked'; +import { ARTICLE_PAGE_LOADED, ARTICLE_PAGE_UNLOADED } from '../../constants/actionTypes'; + +const mapStateToProps = state => ({ + ...state.article, + currentUser: state.common.currentUser +}); + +const mapDispatchToProps = dispatch => ({ + onLoad: payload => + dispatch({ type: ARTICLE_PAGE_LOADED, payload }), + onUnload: () => + dispatch({ type: ARTICLE_PAGE_UNLOADED }) +}); + +class Article extends React.Component { + componentWillMount() { + this.props.onLoad(Promise.all([ + agent.Articles.get(this.props.match.params.id), + agent.Comments.forArticle(this.props.match.params.id) + ])); + } + + componentWillUnmount() { + this.props.onUnload(); + } + + render() { + if (!this.props.article) { + return null; + } + + const markup = { __html: marked(this.props.article.body, { sanitize: true }) }; + const canModify = this.props.currentUser && + this.props.currentUser.username === this.props.article.author.username; + return ( + <div className="article-page"> + + <div className="banner"> + <div className="container"> + + <h1>{this.props.article.title}</h1> + <ArticleMeta + article={this.props.article} + canModify={canModify} /> + + </div> + </div> + + <div className="container page"> + + <div className="row article-content"> + <div className="col-xs-12"> + + <div dangerouslySetInnerHTML={markup}></div> + + <ul className="tag-list"> + { + this.props.article.tagList.map(tag => { + return ( + <li + className="tag-default tag-pill tag-outline" + key={tag}> + {tag} + </li> + ); + }) + } + </ul> + + </div> + </div> + + <hr /> + + <div className="article-actions"> + </div> + + <div className="row"> + <CommentContainer + comments={this.props.comments || []} + errors={this.props.commentErrors} + slug={this.props.match.params.id} + currentUser={this.props.currentUser} /> + </div> + </div> + </div> + ); + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(Article); diff --git a/src/components/ArticleList.js b/src/components/ArticleList.js new file mode 100644 index 0000000000000000000000000000000000000000..1c17836d66dae3ac6b2f506354aaadacf401253c --- /dev/null +++ b/src/components/ArticleList.js @@ -0,0 +1,38 @@ +import ArticlePreview from './ArticlePreview'; +import ListPagination from './ListPagination'; +import React from 'react'; + +const ArticleList = props => { + if (!props.articles) { + return ( + <div className="article-preview">Loading...</div> + ); + } + + if (props.articles.length === 0) { + return ( + <div className="article-preview"> + No articles are here... yet. + </div> + ); + } + + return ( + <div> + { + props.articles.map(article => { + return ( + <ArticlePreview article={article} key={article.slug} /> + ); + }) + } + + <ListPagination + pager={props.pager} + articlesCount={props.articlesCount} + currentPage={props.currentPage} /> + </div> + ); +}; + +export default ArticleList; diff --git a/src/components/ArticlePreview.js b/src/components/ArticlePreview.js new file mode 100644 index 0000000000000000000000000000000000000000..ae9151a54d8043cb76b97c74ab218381832bd775 --- /dev/null +++ b/src/components/ArticlePreview.js @@ -0,0 +1,79 @@ +import React from 'react'; +import { Link } from 'react-router-dom'; +import agent from '../agent'; +import { connect } from 'react-redux'; +import { ARTICLE_FAVORITED, ARTICLE_UNFAVORITED } from '../constants/actionTypes'; + +const FAVORITED_CLASS = 'btn btn-sm btn-primary'; +const NOT_FAVORITED_CLASS = 'btn btn-sm btn-outline-primary'; + +const mapDispatchToProps = dispatch => ({ + favorite: slug => dispatch({ + type: ARTICLE_FAVORITED, + payload: agent.Articles.favorite(slug) + }), + unfavorite: slug => dispatch({ + type: ARTICLE_UNFAVORITED, + payload: agent.Articles.unfavorite(slug) + }) +}); + +const ArticlePreview = props => { + const article = props.article; + const favoriteButtonClass = article.favorited ? + FAVORITED_CLASS : + NOT_FAVORITED_CLASS; + + const handleClick = ev => { + ev.preventDefault(); + if (article.favorited) { + props.unfavorite(article.slug); + } else { + props.favorite(article.slug); + } + }; + + return ( + <div className="article-preview"> + <div className="article-meta"> + <Link to={`/@${article.author.username}`}> + <img src={article.author.image} alt={article.author.username} /> + </Link> + + <div className="info"> + <Link className="author" to={`/@${article.author.username}`}> + {article.author.username} + </Link> + <span className="date"> + {new Date(article.createdAt).toDateString()} + </span> + </div> + + <div className="pull-xs-right"> + <button className={favoriteButtonClass} onClick={handleClick}> + <i className="ion-heart"></i> {article.favoritesCount} + </button> + </div> + </div> + + <Link to={`/article/${article.slug}`} className="preview-link"> + <h1>{article.title}</h1> + <p>{article.description}</p> + <span>Read more...</span> + <ul className="tag-list"> + { + article.tagList.map(tag => { + return ( + <li className="tag-default tag-pill tag-outline" key={tag}> + {tag} + </li> + ) + }) + } + </ul> + </Link> + </div> + ); +} + +export default connect(() => ({}), mapDispatchToProps)(ArticlePreview); diff --git a/src/components/Editor.js b/src/components/Editor.js new file mode 100644 index 0000000000000000000000000000000000000000..751e33bc061b16dd87b7f154901d81c337aa5c9c --- /dev/null +++ b/src/components/Editor.js @@ -0,0 +1,178 @@ +import ListErrors from './ListErrors'; +import React from 'react'; +import agent from '../agent'; +import { connect } from 'react-redux'; +import { + ADD_TAG, + EDITOR_PAGE_LOADED, + REMOVE_TAG, + ARTICLE_SUBMITTED, + EDITOR_PAGE_UNLOADED, + UPDATE_FIELD_EDITOR +} from '../constants/actionTypes'; + +const mapStateToProps = state => ({ + ...state.editor +}); + +const mapDispatchToProps = dispatch => ({ + onAddTag: () => + dispatch({ type: ADD_TAG }), + onLoad: payload => + dispatch({ type: EDITOR_PAGE_LOADED, payload }), + onRemoveTag: tag => + dispatch({ type: REMOVE_TAG, tag }), + onSubmit: payload => + dispatch({ type: ARTICLE_SUBMITTED, payload }), + onUnload: payload => + dispatch({ type: EDITOR_PAGE_UNLOADED }), + onUpdateField: (key, value) => + dispatch({ type: UPDATE_FIELD_EDITOR, key, value }) +}); + +class Editor extends React.Component { + constructor() { + super(); + + const updateFieldEvent = + key => ev => this.props.onUpdateField(key, ev.target.value); + this.changeTitle = updateFieldEvent('title'); + this.changeDescription = updateFieldEvent('description'); + this.changeBody = updateFieldEvent('body'); + this.changeTagInput = updateFieldEvent('tagInput'); + + this.watchForEnter = ev => { + if (ev.keyCode === 13) { + ev.preventDefault(); + this.props.onAddTag(); + } + }; + + this.removeTagHandler = tag => () => { + this.props.onRemoveTag(tag); + }; + + this.submitForm = ev => { + ev.preventDefault(); + const article = { + title: this.props.title, + description: this.props.description, + body: this.props.body, + tagList: this.props.tagList + }; + + const slug = { slug: this.props.articleSlug }; + const promise = this.props.articleSlug ? + agent.Articles.update(Object.assign(article, slug)) : + agent.Articles.create(article); + + this.props.onSubmit(promise); + }; + } + + componentWillReceiveProps(nextProps) { + if (this.props.match.params.slug !== nextProps.match.params.slug) { + if (nextProps.match.params.slug) { + this.props.onUnload(); + return this.props.onLoad(agent.Articles.get(this.props.match.params.slug)); + } + this.props.onLoad(null); + } + } + + componentWillMount() { + if (this.props.match.params.slug) { + return this.props.onLoad(agent.Articles.get(this.props.match.params.slug)); + } + this.props.onLoad(null); + } + + componentWillUnmount() { + this.props.onUnload(); + } + + render() { + return ( + <div className="editor-page"> + <div className="container page"> + <div className="row"> + <div className="col-md-10 offset-md-1 col-xs-12"> + + <ListErrors errors={this.props.errors}></ListErrors> + + <form> + <fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="text" + placeholder="Article Title" + value={this.props.title} + onChange={this.changeTitle} /> + </fieldset> + + <fieldset className="form-group"> + <input + className="form-control" + type="text" + placeholder="What's this article about?" + value={this.props.description} + onChange={this.changeDescription} /> + </fieldset> + + <fieldset className="form-group"> + <textarea + className="form-control" + rows="8" + placeholder="Write your article (in markdown)" + value={this.props.body} + onChange={this.changeBody}> + </textarea> + </fieldset> + + <fieldset className="form-group"> + <input + className="form-control" + type="text" + placeholder="Enter tags" + value={this.props.tagInput} + onChange={this.changeTagInput} + onKeyUp={this.watchForEnter} /> + + <div className="tag-list"> + { + (this.props.tagList || []).map(tag => { + return ( + <span className="tag-default tag-pill" key={tag}> + <i className="ion-close-round" + onClick={this.removeTagHandler(tag)}> + </i> + {tag} + </span> + ); + }) + } + </div> + </fieldset> + + <button + className="btn btn-lg pull-xs-right btn-primary" + type="button" + disabled={this.props.inProgress} + onClick={this.submitForm}> + Publish Article + </button> + + </fieldset> + </form> + + </div> + </div> + </div> + </div> + ); + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(Editor); diff --git a/src/components/Header.js b/src/components/Header.js new file mode 100644 index 0000000000000000000000000000000000000000..63641b8ceddbf3f5a0986ba6d3703cb3474089e7 --- /dev/null +++ b/src/components/Header.js @@ -0,0 +1,91 @@ +import React from 'react'; +import { Link } from 'react-router-dom'; + +const LoggedOutView = props => { + if (!props.currentUser) { + return ( + <ul className="nav navbar-nav pull-xs-right"> + + <li className="nav-item"> + <Link to="/" className="nav-link"> + Home + </Link> + </li> + + <li className="nav-item"> + <Link to="/login" className="nav-link"> + Sign in + </Link> + </li> + + <li className="nav-item"> + <Link to="/register" className="nav-link"> + Sign up + </Link> + </li> + + </ul> + ); + } + return null; +}; + +const LoggedInView = props => { + if (props.currentUser) { + return ( + <ul className="nav navbar-nav pull-xs-right"> + + <li className="nav-item"> + <Link to="/" className="nav-link"> + Home + </Link> + </li> + + <li className="nav-item"> + <Link to="/editor" className="nav-link"> + <i className="ion-compose"></i> New Post + </Link> + </li> + + <li className="nav-item"> + <Link to="/settings" className="nav-link"> + <i className="ion-gear-a"></i> Settings + </Link> + </li> + + <li className="nav-item"> + <Link + to={`/@${props.currentUser.username}`} + className="nav-link"> + <img src={props.currentUser.image} className="user-pic" alt={props.currentUser.username} /> + {props.currentUser.username} + </Link> + </li> + + </ul> + ); + } + + return null; +}; + +class Header extends React.Component { + render() { + return ( + <nav className="navbar navbar-light"> + <div className="container"> + + <Link to="/" className="navbar-brand"> + {this.props.appName.toLowerCase()} + </Link> + + <LoggedOutView currentUser={this.props.currentUser} /> + + <LoggedInView currentUser={this.props.currentUser} /> + </div> + </nav> + ); + } +} + +export default Header; diff --git a/src/components/Home/Banner.js b/src/components/Home/Banner.js new file mode 100644 index 0000000000000000000000000000000000000000..dfb56908d34c9d8d50dcd1e780709bd048dc9508 --- /dev/null +++ b/src/components/Home/Banner.js @@ -0,0 +1,19 @@ +import React from 'react'; + +const Banner = ({ appName, token }) => { + if (token) { + return null; + } + return ( + <div className="banner"> + <div className="container"> + <h1 className="logo-font"> + {appName.toLowerCase()} + </h1> + <p>A place to share your knowledge.</p> + </div> + </div> + ); +}; + +export default Banner; diff --git a/src/components/Home/MainView.js b/src/components/Home/MainView.js new file mode 100644 index 0000000000000000000000000000000000000000..bd581f22c6196a67b043b9c658e6af41e7084bc0 --- /dev/null +++ b/src/components/Home/MainView.js @@ -0,0 +1,96 @@ +import ArticleList from '../ArticleList'; +import React from 'react'; +import agent from '../../agent'; +import { connect } from 'react-redux'; +import { CHANGE_TAB } from '../../constants/actionTypes'; + +const YourFeedTab = props => { + if (props.token) { + const clickHandler = ev => { + ev.preventDefault(); + props.onTabClick('feed', agent.Articles.feed, agent.Articles.feed()); + } + + return ( + <li className="nav-item"> + <a href="" + className={ props.tab === 'feed' ? 'nav-link active' : 'nav-link' } + onClick={clickHandler}> + Your Feed + </a> + </li> + ); + } + return null; +}; + +const GlobalFeedTab = props => { + const clickHandler = ev => { + ev.preventDefault(); + props.onTabClick('all', agent.Articles.all, agent.Articles.all()); + }; + return ( + <li className="nav-item"> + <a + href="" + className={ props.tab === 'all' ? 'nav-link active' : 'nav-link' } + onClick={clickHandler}> + Global Feed + </a> + </li> + ); +}; + +const TagFilterTab = props => { + if (!props.tag) { + return null; + } + + return ( + <li className="nav-item"> + <a href="" className="nav-link active"> + <i className="ion-pound"></i> {props.tag} + </a> + </li> + ); +}; + +const mapStateToProps = state => ({ + ...state.articleList, + tags: state.home.tags, + token: state.common.token +}); + +const mapDispatchToProps = dispatch => ({ + onTabClick: (tab, pager, payload) => dispatch({ type: CHANGE_TAB, tab, pager, payload }) +}); + +const MainView = props => { + return ( + <div className="col-md-9"> + <div className="feed-toggle"> + <ul className="nav nav-pills outline-active"> + + <YourFeedTab + token={props.token} + tab={props.tab} + onTabClick={props.onTabClick} /> + + <GlobalFeedTab tab={props.tab} onTabClick={props.onTabClick} /> + + <TagFilterTab tag={props.tag} /> + + </ul> + </div> + + <ArticleList + pager={props.pager} + articles={props.articles} + loading={props.loading} + articlesCount={props.articlesCount} + currentPage={props.currentPage} /> + </div> + ); +}; + +export default connect(mapStateToProps, mapDispatchToProps)(MainView); diff --git a/src/components/Home/Tags.js b/src/components/Home/Tags.js new file mode 100644 index 0000000000000000000000000000000000000000..fb498ae678412054ca0000176bef3d2ff1fe6a98 --- /dev/null +++ b/src/components/Home/Tags.js @@ -0,0 +1,36 @@ +import React from 'react'; +import agent from '../../agent'; + +const Tags = props => { + const tags = props.tags; + if (tags) { + return ( + <div className="tag-list"> + { + tags.map(tag => { + const handleClick = ev => { + ev.preventDefault(); + props.onClickTag(tag, page => agent.Articles.byTag(tag, page), agent.Articles.byTag(tag)); + }; + + return ( + <a + href="" + className="tag-default tag-pill" + key={tag} + onClick={handleClick}> + {tag} + </a> + ); + }) + } + </div> + ); + } else { + return ( + <div>Loading Tags...</div> + ); + } +}; + +export default Tags; diff --git a/src/components/Home/index.js b/src/components/Home/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1eb04963421ef0f35350a0e9c200ea1b6efdba66 --- /dev/null +++ b/src/components/Home/index.js @@ -0,0 +1,73 @@ +import Banner from './Banner'; +import MainView from './MainView'; +import React from 'react'; +import Tags from './Tags'; +import agent from '../../agent'; +import { connect } from 'react-redux'; +import { + HOME_PAGE_LOADED, + HOME_PAGE_UNLOADED, + APPLY_TAG_FILTER +} from '../../constants/actionTypes'; + +const Promise = global.Promise; + +const mapStateToProps = state => ({ + ...state.home, + appName: state.common.appName, + token: state.common.token +}); + +const mapDispatchToProps = dispatch => ({ + onClickTag: (tag, pager, payload) => + dispatch({ type: APPLY_TAG_FILTER, tag, pager, payload }), + onLoad: (tab, pager, payload) => + dispatch({ type: HOME_PAGE_LOADED, tab, pager, payload }), + onUnload: () => + dispatch({ type: HOME_PAGE_UNLOADED }) +}); + +class Home extends React.Component { + componentWillMount() { + const tab = this.props.token ? 'feed' : 'all'; + const articlesPromise = this.props.token ? + agent.Articles.feed : + agent.Articles.all; + + this.props.onLoad(tab, articlesPromise, Promise.all([agent.Tags.getAll(), articlesPromise()])); + } + + componentWillUnmount() { + this.props.onUnload(); + } + + render() { + return ( + <div className="home-page"> + + <Banner token={this.props.token} appName={this.props.appName} /> + + <div className="container page"> + <div className="row"> + <MainView /> + + <div className="col-md-3"> + <div className="sidebar"> + + <p>Popular Tags</p> + + <Tags + tags={this.props.tags} + onClickTag={this.props.onClickTag} /> + + </div> + </div> + </div> + </div> + + </div> + ); + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(Home); diff --git a/src/components/ListErrors.js b/src/components/ListErrors.js new file mode 100644 index 0000000000000000000000000000000000000000..3b4002260340f547e70f426377ed56347ae89389 --- /dev/null +++ b/src/components/ListErrors.js @@ -0,0 +1,26 @@ +import React from 'react'; + +class ListErrors extends React.Component { + render() { + const errors = this.props.errors; + if (errors) { + return ( + <ul className="error-messages"> + { + Object.keys(errors).map(key => { + return ( + <li key={key}> + {key} {errors[key]} + </li> + ); + }) + } + </ul> + ); + } else { + return null; + } + } +} + +export default ListErrors; diff --git a/src/components/ListPagination.js b/src/components/ListPagination.js new file mode 100644 index 0000000000000000000000000000000000000000..ba38a6e99932546c5adf2cec79965efa40125188 --- /dev/null +++ b/src/components/ListPagination.js @@ -0,0 +1,58 @@ +import React from 'react'; +import agent from '../agent'; +import { connect } from 'react-redux'; +import { SET_PAGE } from '../constants/actionTypes'; + +const mapDispatchToProps = dispatch => ({ + onSetPage: (page, payload) => + dispatch({ type: SET_PAGE, page, payload }) +}); + +const ListPagination = props => { + if (props.articlesCount <= 10) { + return null; + } + + const range = []; + for (let i = 0; i < Math.ceil(props.articlesCount / 10); ++i) { + range.push(i); + } + + const setPage = page => { + if(props.pager) { + props.onSetPage(page, props.pager(page)); + }else { + props.onSetPage(page, agent.Articles.all(page)) + } + }; + + return ( + <nav> + <ul className="pagination"> + + { + range.map(v => { + const isCurrent = v === props.currentPage; + const onClick = ev => { + ev.preventDefault(); + setPage(v); + }; + return ( + <li + className={ isCurrent ? 'page-item active' : 'page-item' } + onClick={onClick} + key={v.toString()}> + + <a className="page-link" href="">{v + 1}</a> + + </li> + ); + }) + } + + </ul> + </nav> + ); +}; + +export default connect(() => ({}), mapDispatchToProps)(ListPagination); diff --git a/src/components/Login.js b/src/components/Login.js new file mode 100644 index 0000000000000000000000000000000000000000..c63a0fa6cb4c6629323412d2b19332b3065d441d --- /dev/null +++ b/src/components/Login.js @@ -0,0 +1,97 @@ +import { Link } from 'react-router-dom'; +import ListErrors from './ListErrors'; +import React from 'react'; +import agent from '../agent'; +import { connect } from 'react-redux'; +import { + UPDATE_FIELD_AUTH, + LOGIN, + LOGIN_PAGE_UNLOADED +} from '../constants/actionTypes'; + +const mapStateToProps = state => ({ ...state.auth }); + +const mapDispatchToProps = dispatch => ({ + onChangeEmail: value => + dispatch({ type: UPDATE_FIELD_AUTH, key: 'email', value }), + onChangePassword: value => + dispatch({ type: UPDATE_FIELD_AUTH, key: 'password', value }), + onSubmit: (email, password) => + dispatch({ type: LOGIN, payload: agent.Auth.login(email, password) }), + onUnload: () => + dispatch({ type: LOGIN_PAGE_UNLOADED }) +}); + +class Login extends React.Component { + constructor() { + super(); + this.changeEmail = ev => this.props.onChangeEmail(ev.target.value); + this.changePassword = ev => this.props.onChangePassword(ev.target.value); + this.submitForm = (email, password) => ev => { + ev.preventDefault(); + this.props.onSubmit(email, password); + }; + } + + componentWillUnmount() { + this.props.onUnload(); + } + + render() { + const email = this.props.email; + const password = this.props.password; + return ( + <div className="auth-page"> + <div className="container page"> + <div className="row"> + + <div className="col-md-6 offset-md-3 col-xs-12"> + <h1 className="text-xs-center">Sign In</h1> + <p className="text-xs-center"> + <Link to="/register"> + Need an account? + </Link> + </p> + + <ListErrors errors={this.props.errors} /> + + <form onSubmit={this.submitForm(email, password)}> + <fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="email" + placeholder="Email" + value={email} + onChange={this.changeEmail} /> + </fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="password" + placeholder="Password" + value={password} + onChange={this.changePassword} /> + </fieldset> + + <button + className="btn btn-lg btn-primary pull-xs-right" + type="submit" + disabled={this.props.inProgress}> + Sign in + </button> + + </fieldset> + </form> + </div> + + </div> + </div> + </div> + ); + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(Login); diff --git a/src/components/Profile.js b/src/components/Profile.js new file mode 100644 index 0000000000000000000000000000000000000000..a3a5e6d1455ccfbef23393020a09f5a82d8a2127 --- /dev/null +++ b/src/components/Profile.js @@ -0,0 +1,170 @@ +import ArticleList from './ArticleList'; +import React from 'react'; +import { Link } from 'react-router-dom'; +import agent from '../agent'; +import { connect } from 'react-redux'; +import { + FOLLOW_USER, + UNFOLLOW_USER, + PROFILE_PAGE_LOADED, + PROFILE_PAGE_UNLOADED +} from '../constants/actionTypes'; + +const EditProfileSettings = props => { + if (props.isUser) { + return ( + <Link + to="/settings" + className="btn btn-sm btn-outline-secondary action-btn"> + <i className="ion-gear-a"></i> Edit Profile Settings + </Link> + ); + } + return null; +}; + +const FollowUserButton = props => { + if (props.isUser) { + return null; + } + + let classes = 'btn btn-sm action-btn'; + if (props.user.following) { + classes += ' btn-secondary'; + } else { + classes += ' btn-outline-secondary'; + } + + const handleClick = ev => { + ev.preventDefault(); + if (props.user.following) { + props.unfollow(props.user.username) + } else { + props.follow(props.user.username) + } + }; + + return ( + <button + className={classes} + onClick={handleClick}> + <i className="ion-plus-round"></i> + + {props.user.following ? 'Unfollow' : 'Follow'} {props.user.username} + </button> + ); +}; + +const mapStateToProps = state => ({ + ...state.articleList, + currentUser: state.common.currentUser, + profile: state.profile +}); + +const mapDispatchToProps = dispatch => ({ + onFollow: username => dispatch({ + type: FOLLOW_USER, + payload: agent.Profile.follow(username) + }), + onLoad: payload => dispatch({ type: PROFILE_PAGE_LOADED, payload }), + onUnfollow: username => dispatch({ + type: UNFOLLOW_USER, + payload: agent.Profile.unfollow(username) + }), + onUnload: () => dispatch({ type: PROFILE_PAGE_UNLOADED }) +}); + +class Profile extends React.Component { + componentWillMount() { + this.props.onLoad(Promise.all([ + agent.Profile.get(this.props.match.params.username), + agent.Articles.byAuthor(this.props.match.params.username) + ])); + } + + componentWillUnmount() { + this.props.onUnload(); + } + + renderTabs() { + return ( + <ul className="nav nav-pills outline-active"> + <li className="nav-item"> + <Link + className="nav-link active" + to={`/@${this.props.profile.username}`}> + My Articles + </Link> + </li> + + <li className="nav-item"> + <Link + className="nav-link" + to={`/@${this.props.profile.username}/favorites`}> + Favorited Articles + </Link> + </li> + </ul> + ); + } + + render() { + const profile = this.props.profile; + if (!profile) { + return null; + } + + const isUser = this.props.currentUser && + this.props.profile.username === this.props.currentUser.username; + + return ( + <div className="profile-page"> + + <div className="user-info"> + <div className="container"> + <div className="row"> + <div className="col-xs-12 col-md-10 offset-md-1"> + + <img src={profile.image} className="user-img" alt={profile.username} /> + <h4>{profile.username}</h4> + <p>{profile.bio}</p> + + <EditProfileSettings isUser={isUser} /> + <FollowUserButton + isUser={isUser} + user={profile} + follow={this.props.onFollow} + unfollow={this.props.onUnfollow} + /> + + </div> + </div> + </div> + </div> + + <div className="container"> + <div className="row"> + + <div className="col-xs-12 col-md-10 offset-md-1"> + + <div className="articles-toggle"> + {this.renderTabs()} + </div> + + <ArticleList + pager={this.props.pager} + articles={this.props.articles} + articlesCount={this.props.articlesCount} + state={this.props.currentPage} /> + </div> + + </div> + </div> + + </div> + ); + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(Profile); +export { Profile, mapStateToProps }; diff --git a/src/components/ProfileFavorites.js b/src/components/ProfileFavorites.js new file mode 100644 index 0000000000000000000000000000000000000000..43ddbbe1897ad1aa505fa01c6079b2d6996fa529 --- /dev/null +++ b/src/components/ProfileFavorites.js @@ -0,0 +1,53 @@ +import { Profile, mapStateToProps } from './Profile'; +import React from 'react'; +import { Link } from 'react-router-dom'; +import agent from '../agent'; +import { connect } from 'react-redux'; +import { + PROFILE_PAGE_LOADED, + PROFILE_PAGE_UNLOADED +} from '../constants/actionTypes'; + +const mapDispatchToProps = dispatch => ({ + onLoad: (pager, payload) => + dispatch({ type: PROFILE_PAGE_LOADED, pager, payload }), + onUnload: () => + dispatch({ type: PROFILE_PAGE_UNLOADED }) +}); + +class ProfileFavorites extends Profile { + componentWillMount() { + this.props.onLoad(page => agent.Articles.favoritedBy(this.props.match.params.username, page), Promise.all([ + agent.Profile.get(this.props.match.params.username), + agent.Articles.favoritedBy(this.props.match.params.username) + ])); + } + + componentWillUnmount() { + this.props.onUnload(); + } + + renderTabs() { + return ( + <ul className="nav nav-pills outline-active"> + <li className="nav-item"> + <Link + className="nav-link" + to={`/@${this.props.profile.username}`}> + My Articles + </Link> + </li> + + <li className="nav-item"> + <Link + className="nav-link active" + to={`/@${this.props.profile.username}/favorites`}> + Favorited Articles + </Link> + </li> + </ul> + ); + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(ProfileFavorites); diff --git a/src/components/Register.js b/src/components/Register.js new file mode 100644 index 0000000000000000000000000000000000000000..ff81749720f1d86cd0bc1e8881767b04f894c26d --- /dev/null +++ b/src/components/Register.js @@ -0,0 +1,113 @@ +import { Link } from 'react-router-dom'; +import ListErrors from './ListErrors'; +import React from 'react'; +import agent from '../agent'; +import { connect } from 'react-redux'; +import { + UPDATE_FIELD_AUTH, + REGISTER, + REGISTER_PAGE_UNLOADED +} from '../constants/actionTypes'; + +const mapStateToProps = state => ({ ...state.auth }); + +const mapDispatchToProps = dispatch => ({ + onChangeEmail: value => + dispatch({ type: UPDATE_FIELD_AUTH, key: 'email', value }), + onChangePassword: value => + dispatch({ type: UPDATE_FIELD_AUTH, key: 'password', value }), + onChangeUsername: value => + dispatch({ type: UPDATE_FIELD_AUTH, key: 'username', value }), + onSubmit: (username, email, password) => { + const payload = agent.Auth.register(username, email, password); + dispatch({ type: REGISTER, payload }) + }, + onUnload: () => + dispatch({ type: REGISTER_PAGE_UNLOADED }) +}); + +class Register extends React.Component { + constructor() { + super(); + this.changeEmail = ev => this.props.onChangeEmail(ev.target.value); + this.changePassword = ev => this.props.onChangePassword(ev.target.value); + this.changeUsername = ev => this.props.onChangeUsername(ev.target.value); + this.submitForm = (username, email, password) => ev => { + ev.preventDefault(); + this.props.onSubmit(username, email, password); + } + } + + componentWillUnmount() { + this.props.onUnload(); + } + + render() { + const email = this.props.email; + const password = this.props.password; + const username = this.props.username; + + return ( + <div className="auth-page"> + <div className="container page"> + <div className="row"> + + <div className="col-md-6 offset-md-3 col-xs-12"> + <h1 className="text-xs-center">Sign Up</h1> + <p className="text-xs-center"> + <Link to="/login"> + Have an account? + </Link> + </p> + + <ListErrors errors={this.props.errors} /> + + <form onSubmit={this.submitForm(username, email, password)}> + <fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="text" + placeholder="Username" + value={this.props.username} + onChange={this.changeUsername} /> + </fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="email" + placeholder="Email" + value={this.props.email} + onChange={this.changeEmail} /> + </fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="password" + placeholder="Password" + value={this.props.password} + onChange={this.changePassword} /> + </fieldset> + + <button + className="btn btn-lg btn-primary pull-xs-right" + type="submit" + disabled={this.props.inProgress}> + Sign up + </button> + + </fieldset> + </form> + </div> + + </div> + </div> + </div> + ); + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(Register); diff --git a/src/components/Settings.js b/src/components/Settings.js new file mode 100644 index 0000000000000000000000000000000000000000..265b17a091a864076ba637b23b3662af26914e31 --- /dev/null +++ b/src/components/Settings.js @@ -0,0 +1,171 @@ +import ListErrors from './ListErrors'; +import React from 'react'; +import agent from '../agent'; +import { connect } from 'react-redux'; +import { + SETTINGS_SAVED, + SETTINGS_PAGE_UNLOADED, + LOGOUT +} from '../constants/actionTypes'; + +class SettingsForm extends React.Component { + constructor() { + super(); + + this.state = { + image: '', + username: '', + bio: '', + email: '', + password: '' + }; + + this.updateState = field => ev => { + const state = this.state; + const newState = Object.assign({}, state, { [field]: ev.target.value }); + this.setState(newState); + }; + + this.submitForm = ev => { + ev.preventDefault(); + + const user = Object.assign({}, this.state); + if (!user.password) { + delete user.password; + } + + this.props.onSubmitForm(user); + }; + } + + componentWillMount() { + if (this.props.currentUser) { + Object.assign(this.state, { + image: this.props.currentUser.image || '', + username: this.props.currentUser.username, + bio: this.props.currentUser.bio, + email: this.props.currentUser.email + }); + } + } + + componentWillReceiveProps(nextProps) { + if (nextProps.currentUser) { + this.setState(Object.assign({}, this.state, { + image: nextProps.currentUser.image || '', + username: nextProps.currentUser.username, + bio: nextProps.currentUser.bio, + email: nextProps.currentUser.email + })); + } + } + + render() { + return ( + <form onSubmit={this.submitForm}> + <fieldset> + + <fieldset className="form-group"> + <input + className="form-control" + type="text" + placeholder="URL of profile picture" + value={this.state.image} + onChange={this.updateState('image')} /> + </fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="text" + placeholder="Username" + value={this.state.username} + onChange={this.updateState('username')} /> + </fieldset> + + <fieldset className="form-group"> + <textarea + className="form-control form-control-lg" + rows="8" + placeholder="Short bio about you" + value={this.state.bio} + onChange={this.updateState('bio')}> + </textarea> + </fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="email" + placeholder="Email" + value={this.state.email} + onChange={this.updateState('email')} /> + </fieldset> + + <fieldset className="form-group"> + <input + className="form-control form-control-lg" + type="password" + placeholder="New Password" + value={this.state.password} + onChange={this.updateState('password')} /> + </fieldset> + + <button + className="btn btn-lg btn-primary pull-xs-right" + type="submit" + disabled={this.state.inProgress}> + Update Settings + </button> + + </fieldset> + </form> + ); + } +} + +const mapStateToProps = state => ({ + ...state.settings, + currentUser: state.common.currentUser +}); + +const mapDispatchToProps = dispatch => ({ + onClickLogout: () => dispatch({ type: LOGOUT }), + onSubmitForm: user => + dispatch({ type: SETTINGS_SAVED, payload: agent.Auth.save(user) }), + onUnload: () => dispatch({ type: SETTINGS_PAGE_UNLOADED }) +}); + +class Settings extends React.Component { + render() { + return ( + <div className="settings-page"> + <div className="container page"> + <div className="row"> + <div className="col-md-6 offset-md-3 col-xs-12"> + + <h1 className="text-xs-center">Your Settings</h1> + + <ListErrors errors={this.props.errors}></ListErrors> + + <SettingsForm + currentUser={this.props.currentUser} + onSubmitForm={this.props.onSubmitForm} /> + + <hr /> + + <button + className="btn btn-outline-danger" + onClick={this.props.onClickLogout}> + Or click here to logout. + </button> + + </div> + </div> + </div> + </div> + ); + } +} + +export default connect(mapStateToProps, mapDispatchToProps)(Settings); diff --git a/src/constants/actionTypes.js b/src/constants/actionTypes.js new file mode 100644 index 0000000000000000000000000000000000000000..8683c60d8f5579deb16eaa5e970c874c2e9478e4 --- /dev/null +++ b/src/constants/actionTypes.js @@ -0,0 +1,36 @@ +export const APP_LOAD = 'APP_LOAD'; +export const REDIRECT = 'REDIRECT'; +export const ARTICLE_SUBMITTED = 'ARTICLE_SUBMITTED'; +export const SETTINGS_SAVED = 'SETTINGS_SAVED'; +export const DELETE_ARTICLE = 'DELETE_ARTICLE'; +export const SETTINGS_PAGE_UNLOADED = 'SETTINGS_PAGE_UNLOADED'; +export const HOME_PAGE_LOADED = 'HOME_PAGE_LOADED'; +export const HOME_PAGE_UNLOADED = 'HOME_PAGE_UNLOADED'; +export const ARTICLE_PAGE_LOADED = 'ARTICLE_PAGE_LOADED'; +export const ARTICLE_PAGE_UNLOADED = 'ARTICLE_PAGE_UNLOADED'; +export const ADD_COMMENT = 'ADD_COMMENT'; +export const DELETE_COMMENT = 'DELETE_COMMENT'; +export const ARTICLE_FAVORITED = 'ARTICLE_FAVORITED'; +export const ARTICLE_UNFAVORITED = 'ARTICLE_UNFAVORITED'; +export const SET_PAGE = 'SET_PAGE'; +export const APPLY_TAG_FILTER = 'APPLY_TAG_FILTER'; +export const CHANGE_TAB = 'CHANGE_TAB'; +export const PROFILE_PAGE_LOADED = 'PROFILE_PAGE_LOADED'; +export const PROFILE_PAGE_UNLOADED = 'PROFILE_PAGE_UNLOADED'; +export const LOGIN = 'LOGIN'; +export const LOGOUT = 'LOGOUT'; +export const REGISTER = 'REGISTER'; +export const LOGIN_PAGE_UNLOADED = 'LOGIN_PAGE_UNLOADED'; +export const REGISTER_PAGE_UNLOADED = 'REGISTER_PAGE_UNLOADED'; +export const ASYNC_START = 'ASYNC_START'; +export const ASYNC_END = 'ASYNC_END'; +export const EDITOR_PAGE_LOADED = 'EDITOR_PAGE_LOADED'; +export const EDITOR_PAGE_UNLOADED = 'EDITOR_PAGE_UNLOADED'; +export const ADD_TAG = 'ADD_TAG'; +export const REMOVE_TAG = 'REMOVE_TAG'; +export const UPDATE_FIELD_AUTH = 'UPDATE_FIELD_AUTH'; +export const UPDATE_FIELD_EDITOR = 'UPDATE_FIELD_EDITOR'; +export const FOLLOW_USER = 'FOLLOW_USER'; +export const UNFOLLOW_USER = 'UNFOLLOW_USER'; +export const PROFILE_FAVORITES_PAGE_UNLOADED = 'PROFILE_FAVORITES_PAGE_UNLOADED'; +export const PROFILE_FAVORITES_PAGE_LOADED = 'PROFILE_FAVORITES_PAGE_LOADED'; \ No newline at end of file diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3d20aa2a6c8f3a2fc62e6f3ec72308c2ab3396fc --- /dev/null +++ b/src/index.js @@ -0,0 +1,20 @@ +import ReactDOM from 'react-dom'; +import { Provider } from 'react-redux'; +import React from 'react'; +import { store, history} from './store'; + +import { Route, Switch } from 'react-router-dom'; +import { ConnectedRouter } from 'react-router-redux'; + +import App from './components/App'; + +ReactDOM.render(( + <Provider store={store}> + <ConnectedRouter history={history}> + <Switch> + <Route path="/" component={App} /> + </Switch> + </ConnectedRouter> + </Provider> + +), document.getElementById('root')); diff --git a/src/middleware.js b/src/middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..9e24a96f9878c712ce047d05f59fcc899093d7fe --- /dev/null +++ b/src/middleware.js @@ -0,0 +1,68 @@ +import agent from './agent'; +import { + ASYNC_START, + ASYNC_END, + LOGIN, + LOGOUT, + REGISTER +} from './constants/actionTypes'; + +const promiseMiddleware = store => next => action => { + if (isPromise(action.payload)) { + store.dispatch({ type: ASYNC_START, subtype: action.type }); + + const currentView = store.getState().viewChangeCounter; + const skipTracking = action.skipTracking; + + action.payload.then( + res => { + const currentState = store.getState() + if (!skipTracking && currentState.viewChangeCounter !== currentView) { + return + } + console.log('RESULT', res); + action.payload = res; + store.dispatch({ type: ASYNC_END, promise: action.payload }); + store.dispatch(action); + }, + error => { + const currentState = store.getState() + if (!skipTracking && currentState.viewChangeCounter !== currentView) { + return + } + console.log('ERROR', error); + action.error = true; + action.payload = error.response.body; + if (!action.skipTracking) { + store.dispatch({ type: ASYNC_END, promise: action.payload }); + } + store.dispatch(action); + } + ); + + return; + } + + next(action); +}; + +const localStorageMiddleware = store => next => action => { + if (action.type === REGISTER || action.type === LOGIN) { + if (!action.error) { + window.localStorage.setItem('jwt', action.payload.user.token); + agent.setToken(action.payload.user.token); + } + } else if (action.type === LOGOUT) { + window.localStorage.setItem('jwt', ''); + agent.setToken(null); + } + + next(action); +}; + +function isPromise(v) { + return v && typeof v.then === 'function'; +} + + +export { promiseMiddleware, localStorageMiddleware } diff --git a/src/reducer.js b/src/reducer.js new file mode 100644 index 0000000000000000000000000000000000000000..5005911af96c07a566569f02ae262c15b72b5019 --- /dev/null +++ b/src/reducer.js @@ -0,0 +1,22 @@ +import article from './reducers/article'; +import articleList from './reducers/articleList'; +import auth from './reducers/auth'; +import { combineReducers } from 'redux'; +import common from './reducers/common'; +import editor from './reducers/editor'; +import home from './reducers/home'; +import profile from './reducers/profile'; +import settings from './reducers/settings'; +import { routerReducer } from 'react-router-redux'; + +export default combineReducers({ + article, + articleList, + auth, + common, + editor, + home, + profile, + settings, + router: routerReducer +}); diff --git a/src/reducers/article.js b/src/reducers/article.js new file mode 100644 index 0000000000000000000000000000000000000000..50ec7a9d5b55ecec496c99bddd76fdc5516b1749 --- /dev/null +++ b/src/reducers/article.js @@ -0,0 +1,35 @@ +import { + ARTICLE_PAGE_LOADED, + ARTICLE_PAGE_UNLOADED, + ADD_COMMENT, + DELETE_COMMENT +} from '../constants/actionTypes'; + +export default (state = {}, action) => { + switch (action.type) { + case ARTICLE_PAGE_LOADED: + return { + ...state, + article: action.payload[0].article, + comments: action.payload[1].comments + }; + case ARTICLE_PAGE_UNLOADED: + return {}; + case ADD_COMMENT: + return { + ...state, + commentErrors: action.error ? action.payload.errors : null, + comments: action.error ? + null : + (state.comments || []).concat([action.payload.comment]) + }; + case DELETE_COMMENT: + const commentId = action.commentId + return { + ...state, + comments: state.comments.filter(comment => comment.id !== commentId) + }; + default: + return state; + } +}; diff --git a/src/reducers/articleList.js b/src/reducers/articleList.js new file mode 100644 index 0000000000000000000000000000000000000000..1fe962daaaeb032f2b8a10dea1ca04c51798c823 --- /dev/null +++ b/src/reducers/articleList.js @@ -0,0 +1,86 @@ +import { + ARTICLE_FAVORITED, + ARTICLE_UNFAVORITED, + SET_PAGE, + APPLY_TAG_FILTER, + HOME_PAGE_LOADED, + HOME_PAGE_UNLOADED, + CHANGE_TAB, + PROFILE_PAGE_LOADED, + PROFILE_PAGE_UNLOADED, + PROFILE_FAVORITES_PAGE_LOADED, + PROFILE_FAVORITES_PAGE_UNLOADED +} from '../constants/actionTypes'; + +export default (state = {}, action) => { + switch (action.type) { + case ARTICLE_FAVORITED: + case ARTICLE_UNFAVORITED: + return { + ...state, + articles: state.articles.map(article => { + if (article.slug === action.payload.article.slug) { + return { + ...article, + favorited: action.payload.article.favorited, + favoritesCount: action.payload.article.favoritesCount + }; + } + return article; + }) + }; + case SET_PAGE: + return { + ...state, + articles: action.payload.articles, + articlesCount: action.payload.articlesCount, + currentPage: action.page + }; + case APPLY_TAG_FILTER: + return { + ...state, + pager: action.pager, + articles: action.payload.articles, + articlesCount: action.payload.articlesCount, + tab: null, + tag: action.tag, + currentPage: 0 + }; + case HOME_PAGE_LOADED: + return { + ...state, + pager: action.pager, + tags: action.payload[0].tags, + articles: action.payload[1].articles, + articlesCount: action.payload[1].articlesCount, + currentPage: 0, + tab: action.tab + }; + case HOME_PAGE_UNLOADED: + return {}; + case CHANGE_TAB: + return { + ...state, + pager: action.pager, + articles: action.payload.articles, + articlesCount: action.payload.articlesCount, + tab: action.tab, + currentPage: 0, + tag: null + }; + case PROFILE_PAGE_LOADED: + case PROFILE_FAVORITES_PAGE_LOADED: + return { + ...state, + pager: action.pager, + articles: action.payload[1].articles, + articlesCount: action.payload[1].articlesCount, + currentPage: 0 + }; + case PROFILE_PAGE_UNLOADED: + case PROFILE_FAVORITES_PAGE_UNLOADED: + return {}; + default: + return state; + } +}; diff --git a/src/reducers/auth.js b/src/reducers/auth.js new file mode 100644 index 0000000000000000000000000000000000000000..6e8383866f86fe2f38d7abbba2d1870e8e655afd --- /dev/null +++ b/src/reducers/auth.js @@ -0,0 +1,34 @@ +import { + LOGIN, + REGISTER, + LOGIN_PAGE_UNLOADED, + REGISTER_PAGE_UNLOADED, + ASYNC_START, + UPDATE_FIELD_AUTH +} from '../constants/actionTypes'; + +export default (state = {}, action) => { + switch (action.type) { + case LOGIN: + case REGISTER: + return { + ...state, + inProgress: false, + errors: action.error ? action.payload.errors : null + }; + case LOGIN_PAGE_UNLOADED: + case REGISTER_PAGE_UNLOADED: + return {}; + case ASYNC_START: + if (action.subtype === LOGIN || action.subtype === REGISTER) { + return { ...state, inProgress: true }; + } + break; + case UPDATE_FIELD_AUTH: + return { ...state, [action.key]: action.value }; + default: + return state; + } + + return state; +}; diff --git a/src/reducers/common.js b/src/reducers/common.js new file mode 100644 index 0000000000000000000000000000000000000000..f95b2bb81b0aec5e9bdc3b7ea230b4ff17617276 --- /dev/null +++ b/src/reducers/common.js @@ -0,0 +1,70 @@ +import { + APP_LOAD, + REDIRECT, + LOGOUT, + ARTICLE_SUBMITTED, + SETTINGS_SAVED, + LOGIN, + REGISTER, + DELETE_ARTICLE, + ARTICLE_PAGE_UNLOADED, + EDITOR_PAGE_UNLOADED, + HOME_PAGE_UNLOADED, + PROFILE_PAGE_UNLOADED, + PROFILE_FAVORITES_PAGE_UNLOADED, + SETTINGS_PAGE_UNLOADED, + LOGIN_PAGE_UNLOADED, + REGISTER_PAGE_UNLOADED +} from '../constants/actionTypes'; + +const defaultState = { + appName: 'Conduit', + token: null, + viewChangeCounter: 0 +}; + +export default (state = defaultState, action) => { + switch (action.type) { + case APP_LOAD: + return { + ...state, + token: action.token || null, + appLoaded: true, + currentUser: action.payload ? action.payload.user : null + }; + case REDIRECT: + return { ...state, redirectTo: null }; + case LOGOUT: + return { ...state, redirectTo: '/', token: null, currentUser: null }; + case ARTICLE_SUBMITTED: + const redirectUrl = `/article/${action.payload.article.slug}`; + return { ...state, redirectTo: redirectUrl }; + case SETTINGS_SAVED: + return { + ...state, + redirectTo: action.error ? null : '/', + currentUser: action.error ? null : action.payload.user + }; + case LOGIN: + case REGISTER: + return { + ...state, + redirectTo: action.error ? null : '/', + token: action.error ? null : action.payload.user.token, + currentUser: action.error ? null : action.payload.user + }; + case DELETE_ARTICLE: + return { ...state, redirectTo: '/' }; + case ARTICLE_PAGE_UNLOADED: + case EDITOR_PAGE_UNLOADED: + case HOME_PAGE_UNLOADED: + case PROFILE_PAGE_UNLOADED: + case PROFILE_FAVORITES_PAGE_UNLOADED: + case SETTINGS_PAGE_UNLOADED: + case LOGIN_PAGE_UNLOADED: + case REGISTER_PAGE_UNLOADED: + return { ...state, viewChangeCounter: state.viewChangeCounter + 1 }; + default: + return state; + } +}; diff --git a/src/reducers/editor.js b/src/reducers/editor.js new file mode 100644 index 0000000000000000000000000000000000000000..fd4563313882910bc8a31ce1443e5e8d60d01806 --- /dev/null +++ b/src/reducers/editor.js @@ -0,0 +1,54 @@ +import { + EDITOR_PAGE_LOADED, + EDITOR_PAGE_UNLOADED, + ARTICLE_SUBMITTED, + ASYNC_START, + ADD_TAG, + REMOVE_TAG, + UPDATE_FIELD_EDITOR +} from '../constants/actionTypes'; + +export default (state = {}, action) => { + switch (action.type) { + case EDITOR_PAGE_LOADED: + return { + ...state, + articleSlug: action.payload ? action.payload.article.slug : '', + title: action.payload ? action.payload.article.title : '', + description: action.payload ? action.payload.article.description : '', + body: action.payload ? action.payload.article.body : '', + tagInput: '', + tagList: action.payload ? action.payload.article.tagList : [] + }; + case EDITOR_PAGE_UNLOADED: + return {}; + case ARTICLE_SUBMITTED: + return { + ...state, + inProgress: null, + errors: action.error ? action.payload.errors : null + }; + case ASYNC_START: + if (action.subtype === ARTICLE_SUBMITTED) { + return { ...state, inProgress: true }; + } + break; + case ADD_TAG: + return { + ...state, + tagList: state.tagList.concat([state.tagInput]), + tagInput: '' + }; + case REMOVE_TAG: + return { + ...state, + tagList: state.tagList.filter(tag => tag !== action.tag) + }; + case UPDATE_FIELD_EDITOR: + return { ...state, [action.key]: action.value }; + default: + return state; + } + + return state; +}; diff --git a/src/reducers/home.js b/src/reducers/home.js new file mode 100644 index 0000000000000000000000000000000000000000..c1cd49af1483ba043bdf4c6e1540e4e2f7c5fd43 --- /dev/null +++ b/src/reducers/home.js @@ -0,0 +1,15 @@ +import { HOME_PAGE_LOADED, HOME_PAGE_UNLOADED } from '../constants/actionTypes'; + +export default (state = {}, action) => { + switch (action.type) { + case HOME_PAGE_LOADED: + return { + ...state, + tags: action.payload[0].tags + }; + case HOME_PAGE_UNLOADED: + return {}; + default: + return state; + } +}; diff --git a/src/reducers/profile.js b/src/reducers/profile.js new file mode 100644 index 0000000000000000000000000000000000000000..5e67a79de7cbad6483cdf3d4f8a971b7e94097b7 --- /dev/null +++ b/src/reducers/profile.js @@ -0,0 +1,24 @@ +import { + PROFILE_PAGE_LOADED, + PROFILE_PAGE_UNLOADED, + FOLLOW_USER, + UNFOLLOW_USER +} from '../constants/actionTypes'; + +export default (state = {}, action) => { + switch (action.type) { + case PROFILE_PAGE_LOADED: + return { + ...action.payload[0].profile + }; + case PROFILE_PAGE_UNLOADED: + return {}; + case FOLLOW_USER: + case UNFOLLOW_USER: + return { + ...action.payload.profile + }; + default: + return state; + } +}; diff --git a/src/reducers/settings.js b/src/reducers/settings.js new file mode 100644 index 0000000000000000000000000000000000000000..8e3751e634ba0e875248feac6720cd725e1ee9b5 --- /dev/null +++ b/src/reducers/settings.js @@ -0,0 +1,25 @@ +import { + SETTINGS_SAVED, + SETTINGS_PAGE_UNLOADED, + ASYNC_START +} from '../constants/actionTypes'; + +export default (state = {}, action) => { + switch (action.type) { + case SETTINGS_SAVED: + return { + ...state, + inProgress: false, + errors: action.error ? action.payload.errors : null + }; + case SETTINGS_PAGE_UNLOADED: + return {}; + case ASYNC_START: + return { + ...state, + inProgress: true + }; + default: + return state; + } +}; diff --git a/src/store.js b/src/store.js new file mode 100644 index 0000000000000000000000000000000000000000..185d866fba9a63469f75a62fbee35656bbfbf7ff --- /dev/null +++ b/src/store.js @@ -0,0 +1,25 @@ +import { applyMiddleware, createStore } from 'redux'; +import { createLogger } from 'redux-logger' +import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly'; +import { promiseMiddleware, localStorageMiddleware } from './middleware'; +import reducer from './reducer'; + +import { routerMiddleware } from 'react-router-redux' +import createHistory from 'history/createBrowserHistory'; + +export const history = createHistory(); + +// Build the middleware for intercepting and dispatching navigation actions +const myRouterMiddleware = routerMiddleware(history); + +const getMiddleware = () => { + if (process.env.NODE_ENV === 'production') { + return applyMiddleware(myRouterMiddleware, promiseMiddleware, localStorageMiddleware); + } else { + // Enable additional logging in non-production environments. + return applyMiddleware(myRouterMiddleware, promiseMiddleware, localStorageMiddleware, createLogger()) + } +}; + +export const store = createStore( + reducer, composeWithDevTools(getMiddleware()));