Repository: knowbody/redux-react-router-example-app
Branch: master
Commit: e8ad0c361442
Files: 43
Total size: 42.0 KB
Directory structure:
gitextract_19bsxdxr/
├── .babelrc
├── .eslintignore
├── .eslintrc
├── .gitignore
├── .travis.yml
├── CODE_OF_CONDUCT.md
├── LICENSE
├── Procfile
├── README.md
├── docs/
│ └── Introduction.md
├── fakeAPI.js
├── index.html
├── package.json
├── server.js
├── src/
│ ├── javascript/
│ │ ├── Root.js
│ │ ├── components/
│ │ │ ├── Footer.js
│ │ │ └── Header.js
│ │ ├── config/
│ │ │ └── urls.js
│ │ ├── containers/
│ │ │ ├── AppBar.js
│ │ │ └── DevTools.js
│ │ ├── decorators/
│ │ │ └── withMaterialUI.js
│ │ ├── hooks.js
│ │ ├── index.js
│ │ ├── redux/
│ │ │ ├── index.js
│ │ │ ├── middleware/
│ │ │ │ ├── clientMiddleware.js
│ │ │ │ ├── index.js
│ │ │ │ ├── logger.js
│ │ │ │ └── request.js
│ │ │ └── modules/
│ │ │ ├── auth.js
│ │ │ ├── blogposts.js
│ │ │ ├── draft.js
│ │ │ ├── reducer.js
│ │ │ ├── users.js
│ │ │ └── utils/
│ │ │ └── fetch.js
│ │ └── views/
│ │ ├── Blog/
│ │ │ ├── Post.js
│ │ │ └── index.js
│ │ ├── Draft/
│ │ │ └── index.js
│ │ └── Login/
│ │ └── index.js
│ └── styles/
│ └── main.less
├── test/
│ ├── fixture/
│ │ └── data.js
│ └── index.spec.js
├── webpack.config.js
└── webpack.config.production.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc
================================================
{
"stage": 0
}
================================================
FILE: .eslintignore
================================================
lib
node_modules
================================================
FILE: .eslintrc
================================================
{
"extends": "eslint-config-airbnb",
"env": {
"browser": true,
"es6": true,
"mocha": true,
"node": true
},
"rules": {
"eol-last": 2,
"max-len": [2, 100, 4],
"no-underscore-dangle": [0],
"comma-dangle": [2, "never"],
"no-var": 2,
"react/display-name": 0,
"react/jsx-boolean-value": 2,
"react/jsx-quotes": "prefer-single",
"react/jsx-no-undef": 2,
"react/jsx-sort-props": 0,
"react/jsx-uses-react": 2,
"react/jsx-uses-vars": 2,
"react/no-did-mount-set-state": 2,
"react/no-did-update-set-state": 2,
"react/no-multi-comp": 0,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/react-in-jsx-scope": 2,
"react/self-closing-comp": 2,
"react/wrap-multilines": 2,
"space-before-function-paren": [2, {
"anonymous": "always",
"named": "never"
}],
"strict": [2, "global"],
"react/react-in-jsx-scope": 2,
//Temporarirly disabled due to a possible bug in babel-eslint (todomvc example)
"block-scoped-var": 0,
// Temporarily disabled for test/* until babel/babel-eslint#33 is resolved
"padded-blocks": 0
},
"plugins": [
"react"
]
}
================================================
FILE: .gitignore
================================================
node_modules
npm-debug.log
.DS_Store
dist
static
================================================
FILE: .travis.yml
================================================
language: node_js
node_js:
- "iojs"
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Code of Conduct
As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2015 Mateusz Zatorski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: Procfile
================================================
web: npm run deploy
================================================
FILE: README.md
================================================
Redux and React Router Example App
===
[](https://travis-ci.org/knowbody/redux-react-router-example-app)
**This project is a work in progress.**

### Why
This project was started, because I found myself and many developers would like to get
an insight on how Redux and React Router can be used in the bigger projects than a TODO app.
Feel free to contribute to make it a great start point for others.
#### Redux
The redux structure follows the [ducks modular redux proposal](https://github.com/erikras/ducks-modular-redux)
### About
Example blog app built with React, Redux and React Router.
### Get started
1. `npm install && npm start`
### License
MIT ([http://www.opensource.org/licenses/mit-license.php](http://www.opensource.org/licenses/mit-license.php))
================================================
FILE: docs/Introduction.md
================================================
# Introduction
**Why?** This project was started, because I found myself and many developers would like to get
an insight on how Redux and React Router can be used in the bigger projects than a TODO app.
I also wanted to give a chance to people who want start contributing to open source.
### The Goal
The goal is to build a "fully featured" blog-like application. At the moment the project
is in the very early stage and I know that is still missing a lot of things.
Please feel free to contribute to the project by sending an issue or a PR,
so the others can benefit from this project.
### There is more
I plan to document the things we build here so it will be easy for the beginners to understand
how to start.
================================================
FILE: fakeAPI.js
================================================
/* eslint-disable */
var jsonServer = require('json-server');
var data = require('./test/fixture/data');
var server = jsonServer.create();
var router = jsonServer.router(data);
server.use(jsonServer.defaults());
server.use(router);
server.listen(3010, 'localhost', function (err) {
if (err) {
console.log(err);
}
console.log('Fake API listening at localhost:3010');
});
================================================
FILE: index.html
================================================
React Redux Boilerplate
================================================
FILE: package.json
================================================
{
"name": "redux-blogapp",
"version": "0.0.1",
"description": "Redux and React Router Blogapp example",
"author": "Mateusz Zatorski (https://github.com/knowbody)",
"main": "server.js",
"scripts": {
"start": "node server.js",
"lint": "`npm bin`/eslint src/javascript",
"deploy": "export NODE_ENV=production && `npm bin`/webpack --config webpack.config.production.js && npm start",
"test": "NODE_ENV=test mocha --compilers js:babel/register --recursive",
"test:watch": "NODE_ENV=test mocha --compilers js:babel/register --recursive --watch",
"test:cov": "babel-node ./node_modules/.bin/isparta cover ./node_modules/.bin/_mocha -- --recursive"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/knowbody/redux-react-router-example-app/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/knowbody/redux-react-router-example-app.git"
},
"homepage": "https://github.com/knowbody/redux-react-router-example-app",
"dependencies": {
"classnames": "^2.2.0",
"express": "^4.13.3",
"history": "^1.13.1",
"material-ui": "^0.13.0",
"normalize.css": "^3.0.3",
"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-redux": "^4.0.0",
"react-router": "^1.0.0",
"react-tap-event-plugin": "^0.2.1",
"redux": "^3.0.4",
"redux-form": "^3.0.0-beta-2",
"redux-thunk": "^1.0.0"
},
"devDependencies": {
"babel": "^5.8.29",
"babel-core": "^5.8.30",
"babel-eslint": "^4.1.3",
"babel-loader": "^5.3.2",
"babel-plugin-react-transform": "^1.1.1",
"casual": "^1.4.7",
"css-loader": "^0.15.6",
"eslint": "^1.7.3",
"eslint-config-airbnb": "0.1.0",
"eslint-plugin-react": "^3.6.3",
"expect": "^1.12.2",
"file-loader": "^0.8.4",
"isparta": "^3.1.0",
"json-server": "^0.8.2",
"less": "^2.5.3",
"less-loader": "^2.2.1",
"mocha": "^2.3.3",
"node-libs-browser": "^0.5.3",
"raw-loader": "^0.5.1",
"react-transform-catch-errors": "^1.0.0",
"react-transform-hmr": "^1.0.1",
"redbox-react": "1.2.6",
"redux-devtools": "^3.0.1",
"redux-devtools-dock-monitor": "^1.0.1",
"redux-devtools-log-monitor": "^1.0.2",
"style-loader": "^0.13.0",
"todomvc-app-css": "^2.0.1",
"url-loader": "^0.5.6",
"webpack": "^1.12.2",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.4.1"
}
}
================================================
FILE: server.js
================================================
/* eslint-disable */
var isDev = (process.env.NODE_ENV !== 'production');
var webpack = require('webpack');
var express = require('express');
var path = require('path');
var app = express();
if (!isDev) {
var static_path = path.join(__dirname);
app.use(express.static(static_path))
.get('/', function (req, res) {
res.sendFile('./index.html', {
root: static_path
});
}).listen(process.env.PORT || 8080, function (err) {
if (err) { console.log(err) };
console.log('Listening at localhost:8080');
});
}
if (isDev) {
var config = require('./webpack.config');
var compiler = webpack(config);
require('./fakeAPI');
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at localhost:3000');
});
}
================================================
FILE: src/javascript/Root.js
================================================
import React, { Component, PropTypes } from 'react';
import { Router, Route } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { Provider } from 'react-redux';
import { store } from './redux';
import withMaterialUI from './decorators/withMaterialUI';
import * as hooks from './hooks';
// Redux DevTools
import DevTools from './containers/DevTools';
import Blog from './views/Blog';
import Draft from './views/Draft';
import Login from './views/Login';
hooks.bootstrap(store)();
@withMaterialUI
export default class Root extends Component {
render() {
return (
);
}
};
================================================
FILE: src/javascript/components/Footer.js
================================================
import React, { Component } from 'react';
const styles = {
layout: {
height: '100px'
},
footerText: {
textAlign: 'right',
padding: '40px 0',
fontSize: '10px'
}
};
export default class Footer extends Component {
render() {
return (
);
}
}
================================================
FILE: src/javascript/components/Header.js
================================================
import React, { PropTypes, Component } from 'react';
import { AppBar, IconButton, Styles } from 'material-ui';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import MenuItem from 'material-ui/lib/menus/menu-item';
import NavigationMoreVert from 'material-ui/lib/svg-icons/navigation/more-vert';
import ActionAccountCicle
from 'material-ui/lib/svg-icons/action/account-circle';
import SocialGithub from '../../images/GitHub-Mark-Light-120px-plus.png';
export default class Header extends Component {
static contextTypes = {
history: PropTypes.object.isRequired
}
getStyles() {
return {
iconButton: {
color: Styles.Colors.white
},
link: {
display: 'inline-block',
height: 48,
width: 48,
textAlign: 'center'
},
image: {
height: 24,
width: 24
}
};
}
render() {
const { history } = this.context;
const styles = this.getStyles();
const iconElementRight = (
}>
} primaryText='Login'
onTouchTap={() => history.pushState(null, '/login')} />
);
return (
}
iconElementRight={iconElementRight} />
);
}
}
================================================
FILE: src/javascript/config/urls.js
================================================
export const api = 'http://localhost:3010';
================================================
FILE: src/javascript/containers/AppBar.js
================================================
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Header from '../components/Header';
import Footer from '../components/Footer';
class AppBar extends Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
children: PropTypes.oneOfType([
PropTypes.object,
PropTypes.array
])
}
getStyles() {
return {
main: {
maxWidth: 950,
margin: '0 auto',
paddingTop: 10
}
};
}
render() {
const styles = this.getStyles();
return (
{this.props.children}
);
}
}
export default connect()(AppBar);
================================================
FILE: src/javascript/containers/DevTools.js
================================================
import React from 'react';
// Exported from redux-devtools
import { createDevTools } from 'redux-devtools';
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
// createDevTools takes a monitor and produces a DevTools component
const DevTools = createDevTools(
);
export default DevTools;
================================================
FILE: src/javascript/decorators/withMaterialUI.js
================================================
import React, { Component } from 'react';
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import LightRawTheme from 'material-ui/lib/styles/raw-themes/light-raw-theme';
export default function withMaterialUI(ComposedComponent) {
return class MaterialUI extends Component {
/*
For more details: https://github.com/callemall/material-ui#usage
Pass material-ui theme through child context
We are doing this here so we don't have to do it anywhere else.
*/
static childContextTypes = {
muiTheme: React.PropTypes.object
}
getChildContext() {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme)
};
}
render() {
const { context, ...other } = this.props;
return ;
}
};
}
================================================
FILE: src/javascript/hooks.js
================================================
import { bindActionCreators } from 'redux';
import * as UserActions from './redux/modules/users';
import * as BlogActions from './redux/modules/blogposts';
export function bootstrap({ dispatch }) {
const userActions = bindActionCreators(UserActions, dispatch);
const blogActions = bindActionCreators(BlogActions, dispatch);
return () => {
blogActions.fetchPosts(0, 10);
userActions.fetchUsers();
};
}
export function editPost({ dispatch }) {
const actions = bindActionCreators(BlogActions, dispatch);
return ({ params }) => {
actions.setDraft(parseInt(params.id, 10));
};
}
================================================
FILE: src/javascript/index.js
================================================
import 'babel/polyfill';
import React from 'react';
import { render } from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import createHashHistory from 'history/lib/createHashHistory';
import Root from './Root';
/*
Needed for onTouchTap
Can go away when react 1.0 release
Check this repo:
https://github.com/zilverline/react-tap-event-plugin
*/
injectTapEventPlugin();
render(, document.getElementById('root'));
================================================
FILE: src/javascript/redux/index.js
================================================
import { createStore, applyMiddleware, compose } from 'redux';
import { devTools, persistState } from 'redux-devtools';
import middleware from './middleware';
import reducer from './modules/reducer';
import DevTools from '../containers/DevTools';
let finalCreateStore;
if (__DEVELOPMENT__ && __DEVTOOLS__) {
finalCreateStore = compose(
applyMiddleware.apply(this, middleware),
// Provides support for DevTools:
DevTools.instrument(),
// Optional. Lets you write ?debug_session= in address bar to persist debug sessions
persistState(getDebugSessionKey())
)(createStore);
} else {
finalCreateStore = compose(
applyMiddleware.apply(this, middleware)
)(createStore);
}
function getDebugSessionKey() {
// You can write custom logic here!
// By default we try to read the key from ?debug_session= in the address bar
const matches = window.location.href.match(/[?&]debug_session=([^&]+)\b/);
return (matches && matches.length > 0)? matches[1] : null;
}
export const store = finalCreateStore(reducer);
================================================
FILE: src/javascript/redux/middleware/clientMiddleware.js
================================================
export default function clientMiddleware(client) {
return ({dispatch, getState}) => {
return next => action => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
const { promise, types, ...rest } = action;
if (!promise) {
return next(action);
}
const [REQUEST, SUCCESS, FAILURE] = types;
next({...rest, type: REQUEST});
return promise(client).then(
(result) => next({...rest, result, type: SUCCESS}),
(error) => next({...rest, error, type: FAILURE})
).catch((error)=> {
console.error('MIDDLEWARE ERROR:', error);
next({...rest, error, type: FAILURE});
});
};
};
}
================================================
FILE: src/javascript/redux/middleware/index.js
================================================
import thunk from 'redux-thunk';
import logger from './logger';
import request from './request';
export default [
thunk,
request,
logger
];
================================================
FILE: src/javascript/redux/middleware/logger.js
================================================
/**
* Logs previous and current state for every action call
* @param getState
* @returns {Function}
*/
export default function logger({ getState }) {
return (next) => (action) => {
console.log('dispatching', action);// eslint-disable-line
const result = next(action);
console.log('next state', getState());// eslint-disable-line
return result;
};
}
================================================
FILE: src/javascript/redux/middleware/request.js
================================================
import * as urls from '../../config/urls';
import { defaultParams as defaultFetchParams } from '../modules/utils/fetch';
export default function request({ dispatch }) {
return (next) => async (action) => {
const { type, payload = null, meta = {} } = action;
if (!type || type.constructor !== Array) return next(action);
const [BEGIN, SUCCESS, FAILURE] = action.type;
let [url, fetchParams] = meta.fetch;
dispatch({
type: BEGIN,
payload: payload
});
fetchParams = {
...defaultFetchParams,
...fetchParams
};
if (url.match(/^http/) === null) url = `${urls.api}${url}`;
const response = await fetch(url, fetchParams);
const json = await response.json();
if (response.status >= 200 && response.status < 300) {
dispatch({
type: SUCCESS,
payload: fetchParams.method === 'delete' ? payload : json
});
} else {
dispatch({
type: FAILURE,
error: true,
payload: fetchParams.method === 'delete' ? payload : json
});
}
};
}
================================================
FILE: src/javascript/redux/modules/auth.js
================================================
const LOGIN = 'auth/LOGIN';
const LOGIN_SUCCESS = 'auth/LOGIN_SUCCESS';
const LOGIN_FAILURE = 'auth/LOGIN_FAILURE';
const REGISTER = 'auth/REGISTER';
const REGISTER_SUCCESS = 'auth/REGISTER_SUCCESS';
const REGISTER_FAILURE = 'auth/REGISTER_FAILURE';
const initialState = {
user: {
id: 1,
username: 'johndoe',
email: 'john.doe@gmail.com',
password: 'demo',
avatar: 'https://randomuser.me/api/portraits/med/women/1.jpg',
firstname: 'John',
lastname: 'Doe'
}
};
export default function reducer(state = initialState, action = {}) {
const { type } = action;
switch (type) {
default:
return state;
}
}
// export function login(username, password) {
// return (dispatch, getState) => {
// dispatch({
// type: LOGIN,
// payload: {
// username,
// password
// }
// });
// // Do something async here then dispatch LOGIN_SUCCESS or LOGIN_FAILURE
// setTimeout(() => {
// dispatch({
// type: LOGIN_SUCCESS,
// payload: {
// username,
// password
// },
// meta: 'The optional meta property MAY be any type of value. It is \
// intended for any extra information that is not part of the payload.\
// It will still be accessible in the reduxer. You could use it for\
// some middleware to debug your code'
// });
// }, 1000);
// };
// }
// export function register(username, email, password) {
// return (dispatch, getState) => {
// dispatch({
// type: REGISTER,
// payload: {
// username,
// email,
// password
// }
// });
// // Do something async here then dispatch LOGIN_SUCCESS or LOGIN_FAILURE
// setTimeout(() => {
// dispatch({
// type: REGISTER_FAILURE,
// payload: new Error(),
// error: true
// });
// }, 1000);
// }
// }
================================================
FILE: src/javascript/redux/modules/blogposts.js
================================================
const FETCH_POSTS = 'blogposts/FETCH_POSTS';
const FETCH_POSTS_SUCCESS = 'blogposts/FETCH_POSTS_SUCCESS';
const FETCH_POSTS_FAILURE = 'blogposts/FETCH_POSTS_FAILURE';
const CREATE_POST = 'blogposts/CREATE_POST';
const CREATE_POST_SUCCESS = 'blogposts/CREATE_POST_SUCCESS';
const CREATE_POST_FAILURE = 'blogposts/CREATE_POST_FAILURE';
const READ_POST = 'blogposts/READ_POST';
const READ_POST_SUCCESS = 'blogposts/READ_POST_SUCCESS';
const READ_POST_FAILURE = 'blogposts/READ_POST_FAILURE';
const UPDATE_POST = 'blogposts/UPDATE_POST';
const UPDATE_POST_SUCCESS = 'blogposts/UPDATE_POST_SUCCESS';
const UPDATE_POST_FAILURE = 'blogposts/UPDATE_POST_FAILURE';
const REMOVE_POST = 'blogposts/REMOVE_POST';
const REMOVE_POST_SUCCESS = 'blogposts/REMOVE_POST_SUCCESS';
const REMOVE_POST_FAILURE = 'blogposts/REMOVE_POST_FAILURE';
export const SET_DRAFT = 'draft/SET_DRAFT';
export const UPDATE_DRAFT = 'draft/UPDATE_DRAFT';
const initialState = [];
function indexOfObjectById(arr, obj) {
for (let i = 0, length = arr.length; i < length; i++) {
if (arr[i].id === obj.id) return i;
}
}
export default function reducer(state = initialState, action = {}) {
const { type, payload } = action;
switch (type) {
case FETCH_POSTS_SUCCESS:
return [...payload];
case CREATE_POST_SUCCESS:
return [{
id: (state.length === 0)
? 1
: Math.max.apply(state.map(post => post.id)) + 1,
title: payload.title,
subtitle: payload.subtitle,
poster: payload.poster,
body: payload.body,
user: payload.user
}, ...state];
case UPDATE_POST_SUCCESS:
const index = indexOfObjectById(state, payload);
const oldPost = state[index];
const newState = [...state];
newState.splice(index, 1, {...oldPost, ...payload});
return newState;
case REMOVE_POST_SUCCESS:
return state.filter(blogpost =>
blogpost.id !== payload.id
);
default:
return state;
}
}
export function fetchPosts(start = 0, limit = 10) {
return async (dispatch) => {
dispatch({
type: [FETCH_POSTS, FETCH_POSTS_SUCCESS, FETCH_POSTS_FAILURE],
meta: {
fetch: [`/post?_start=${start}&_limit=${limit}`, {method: 'get'}]
}
});
};
}
export function createPost(post) {
return async (dispatch, getState) => {
const { auth } = getState();
post.user = auth.user.id;
dispatch({
type: [CREATE_POST, CREATE_POST_SUCCESS, CREATE_POST_FAILURE],
payload: post,
meta: {
fetch: ['/post', {method: 'post', body: JSON.stringify(post)}]
}
});
};
}
export function readPost(id) {
return async (dispatch) => {
dispatch({
type: [READ_POST, READ_POST_SUCCESS, READ_POST_FAILURE],
meta: {
fetch: [`/post/${id}`, {method: 'get'}]
}
});
};
}
export function updatePost(post) {
return async (dispatch) => {
dispatch({
type: [UPDATE_POST, UPDATE_POST_SUCCESS, UPDATE_POST_FAILURE],
payload: post,
meta: {
fetch: [`/post/${post.id}`, {method: 'put', body: JSON.stringify(post)}]
}
});
};
}
/**
* Deletes a post
* @param post
* @returns {Function}
*/
export function removePost(post) {
return async (dispatch) => {
dispatch({
type: [REMOVE_POST, REMOVE_POST_SUCCESS, REMOVE_POST_FAILURE],
payload: post,
meta: {
fetch: [`/post/${post.id}`, {method: 'delete'}]
}
});
};
}
/**
* Action is used to set post as draft
* @param postId
* @returns {Function}
*/
export function setDraft(postId) {
return (dispatch, getState) => {
const { blogposts } = getState();
const post = blogposts.filter(obj => obj.id === postId)[0];
if (!post) return;
dispatch({
type: SET_DRAFT,
payload: post
});
};
}
/**
* Action to set current draft
* @param {object} draft
* @returns {{type: UPDATE_DRAFT, payload: {object}}}
*/
export function updateDraft(draft) {
return {
type: UPDATE_DRAFT,
payload: draft
};
}
================================================
FILE: src/javascript/redux/modules/draft.js
================================================
const CREATE_POST_SUCCESS = 'draft/CREATE_POST_SUCCESS';
const UPDATE_POST_SUCCESS = 'draft/UPDATE_POST_SUCCESS';
export const SET_DRAFT = 'draft/SET_DRAFT';
export const UPDATE_DRAFT = 'draft/UPDATE_DRAFT';
const initialState = {
title: '',
subtitle: '',
poster: `http://thecatapi.com/api/images/get?type=jpg&r='${Math.random()}`,
body: ''
};
export default function reducer(state = initialState, action = {}) {
const { type, payload } = action;
switch (type) {
case CREATE_POST_SUCCESS:
return {
...initialState,
poster: `http://thecatapi.com/api/images/get?type=jpg&r='${Math.random()}`
};
case UPDATE_POST_SUCCESS:
return {
...initialState,
poster: `http://thecatapi.com/api/images/get?type=jpg&r='${Math.random()}`
};
case SET_DRAFT:
return { ...payload };
case UPDATE_DRAFT:
return { ...state, ...payload };
default:
return state;
}
}
================================================
FILE: src/javascript/redux/modules/reducer.js
================================================
import { combineReducers } from 'redux';
import { reducer as form } from 'redux-form';
import auth from './auth';
import users from './users';
import blogposts from './blogposts';
import draft from './draft';
export default combineReducers({
auth,
users,
blogposts,
draft,
form
});
================================================
FILE: src/javascript/redux/modules/users.js
================================================
const FETCH_USERS = 'users/FETCH_USERS';
const initialState = [];
export default function reducer(state = initialState, action = {}) {
const { type, payload } = action;
switch (type) {
case FETCH_USERS:
return [...payload];
default:
return state;
}
}
import * as urls from '../../config/urls';
import {read} from './utils/fetch';
export function fetchUsers() {
return async (dispatch) => {
const response = await read(`${urls.api}/user`);
const posts = await response.json();
dispatch({
type: FETCH_USERS,
payload: posts
});
};
}
================================================
FILE: src/javascript/redux/modules/utils/fetch.js
================================================
export const defaultParams = {
mode: 'cors',
credentials: 'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8'
}
};
/**
* HTTP GET
* @param {string} url
* @return {Promise}
*/
export function read(url) {
return fetch(url, {
...defaultParams,
method: 'get'
});
}
/**
* HTTP POST
* @param {string} url
* @param {object} body
* @return {Promise}
*/
export function create(url, body = {}) {
return fetch(url, {
...defaultParams,
method: 'post',
body: JSON.stringify(body)
});
}
/**
* HTTP PUT
* @param {string} url
* @param {object} body
* @return {Promise}
*/
export function update(url, body = {}) {
return fetch(url, {
...defaultParams,
method: 'put',
body: JSON.stringify(body)
});
}
/**
* HTTP DELETE
* @param {string} url
* @return {Promise}
*/
export function destroy(url) {
return fetch(url, {
...defaultParams,
method: 'delete'
});
}
================================================
FILE: src/javascript/views/Blog/Post.js
================================================
import React, { Component, PropTypes } from 'react';
import {
Card,
CardHeader,
CardMedia,
CardTitle,
CardText,
IconButton
} from 'material-ui';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import MenuItem from 'material-ui/lib/menus/menu-item';
import NavigationMoreVert from 'material-ui/lib/svg-icons/navigation/more-vert';
import EditorModeEdit from 'material-ui/lib/svg-icons/editor/mode-edit';
import ActionDelete from 'material-ui/lib/svg-icons/action/delete';
import SocialShare from 'material-ui/lib/svg-icons/social/share';
export default class Blogpost extends Component {
static propTypes = {
actions: PropTypes.shape({
editPost: PropTypes.func,
removePost: PropTypes.func
}).isRequired,
post: PropTypes.object.isRequired,
user: PropTypes.object.isRequired
}
static contextTypes = {
history: PropTypes.object.isRequired,
muiTheme: PropTypes.object
}
static defaultProps = {
post: {},
user: {}
}
getStyles() {
return {
card: {
position: 'relative',
marginTop: 10,
marginBottom: 20
},
iconMenu: {
position: 'absolute',
top: 12,
right: 16,
zIndex: 5
},
cardMedia: {
marginTop: 20,
background: 'black',
minHeight: 100
},
cardMediaStyle: {
maxHeight: '500px',
textAlign: 'center'
},
cardMediaImage: {
maxHeight: '500px',
maxWidth: '100%'
}
};
}
render() {
const { history } = this.context;
const { actions, post, user } = this.props;
const styles = this.getStyles();
let title = ;
if (post.poster) {
title = (
);
}
return (
}>
} primaryText='Edit'
onTouchTap={() => {
history.pushState(null, `/post/${post.id}/edit`);
}}/>
} primaryText='Remove'
onTouchTap={actions.removePost.bind(null, post)}/>
} primaryText='Share'/>
{title}
{ post.body ? {post.body} : '' }
);
}
}
================================================
FILE: src/javascript/views/Blog/index.js
================================================
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import AppBar from '../../containers/AppBar';
import { FloatingActionButton } from 'material-ui';
import ContentAdd from 'material-ui/lib/svg-icons/content/add';
import Post from './Post';
import * as BlogActions from '../../redux/modules/blogposts';
class BlogApp extends Component {
static propTypes = {
blogposts: PropTypes.array.isRequired,
users: PropTypes.array.isRequired,
dispatch: PropTypes.func.isRequired
}
static contextTypes = {
history: PropTypes.object.isRequired
}
getStyles() {
return {
addContent: {
position: 'fixed',
right: 20,
bottom: 20,
zIndex: 100
}
};
}
render() {
const { history } = this.context;
const { blogposts, users, dispatch } = this.props;
const actions = bindActionCreators(BlogActions, dispatch);
const styles = this.getStyles();
return (
{blogposts.map((post, i) =>
user.id === post.user)[0]}
actions={actions}/>
)}
{
history.pushState(null, '/post/new');
}}>
);
}
}
export default connect(state => ({
blogposts: state.blogposts,
users: state.users
}))(BlogApp);
================================================
FILE: src/javascript/views/Draft/index.js
================================================
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import AppBar from '../../containers/AppBar';
import { Paper, TextField, RaisedButton } from 'material-ui';
import * as BlogActions from '../../redux/modules/blogposts';
class Draft extends Component {
static propTypes = {
params: PropTypes.object.isRequired,
draft: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired
}
static contextTypes = {
history: PropTypes.object.isRequired
}
onSubmit(actions, payload) {
event.preventDefault();
const { history } = this.context;
const { params } = this.props;
const isEdit = history.isActive(`/post/${params.id}/edit`);
isEdit ? actions.updatePost(payload) : actions.createPost(payload);
history.pushState(null, '/');
}
getStyles() {
return {
paper: {
padding: 20
},
form: {
margin: 0
},
textField: {
width: '100%'
},
submit: {
float: 'right',
marginTop: 10
}
};
}
render() {
const { history } = this.context;
const { draft, dispatch, params } = this.props;
const actions = bindActionCreators(BlogActions, dispatch);
const { updateDraft } = actions;
const styles = this.getStyles();
const isEdit = history.isActive(`/post/${params.id}/edit`);
const form = (
);
return (
{form}
);
}
}
export default connect(state => ({draft: state.draft}))(Draft);
================================================
FILE: src/javascript/views/Login/index.js
================================================
import React, { PropTypes, Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Paper, TextField, RaisedButton } from 'material-ui';
import ActionAccountCicle
from 'material-ui/lib/svg-icons/action/account-circle';
import * as AuthActions from '../../redux/modules/auth';
class Login extends Component {
static propTypes = {
dispatch: PropTypes.func.isRequired
}
static contextTypes = {
muiTheme: PropTypes.object.isRequired
}
getStyles() {
return {
center: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
padding: 10
},
paper: {
maxHeight: 400,
maxWidth: 400,
textAlign: 'center',
padding: '20px 40px'
},
submit: {
marginTop: 10,
marginBottom: 20,
width: '100%'
}
};
}
render() {
const styles = this.getStyles();
return (
);
}
submit(event) {
const { dispatch } = this.props;
const actions = bindActionCreators(AuthActions, dispatch);
const identity = this.refs.identity.state.hasValue;
const password = this.refs.password.state.hasValue;
if (event.type === 'keydown' && event.keyCode !== 13) return;
actions.login(identity, password);
}
}
export default connect(state => ({ user: state.user }))(Login);
================================================
FILE: src/styles/main.less
================================================
// Reset
@import '~normalize.css/normalize.css';
// Correct some stuff in scaffolding.less
svg {
box-sizing: content-box;
}
================================================
FILE: test/fixture/data.js
================================================
var casual = require('casual');
var arrayOf = function(times, type) {
var result = [];
for (var i = 0; i < times; ++i) {
result.push(casual[type]);
}
return result;
};
var data = {};
var randGender = ['men', 'women'][Math.floor(Math.random() * 2)];
var baseUrl = 'https://randomuser.me/api/portraits/med/';
var userId = 0;
casual.define('user', function() {
++userId;
return {
id: userId,
username: casual.username,
email: casual.email,
password: 'demo',
avatar: baseUrl + randGender + '/' + userId + '.jpg',
firstname: casual.first_name,
lastname: casual.last_name
};
});
var postId = 0;
casual.define('post', function() {
++postId;
return {
id: postId,
title: casual.title,
subtitle: casual.title,
poster: 'http://thecatapi.com/api/images/get?type=jpg&r=' + postId,
body: casual.text,
user: Math.floor(Math.random() * 99 + 1)
};
});
data.user = arrayOf(100, 'user');
data.post = arrayOf(1000, 'post');
module.exports = data;
================================================
FILE: test/index.spec.js
================================================
================================================
FILE: webpack.config.js
================================================
/* eslint-disable */
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
'./src/javascript/index'
],
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
__DEVELOPMENT__: true,
__DEVTOOLS__: true
})
],
resolve: {
alias: {
'redux': path.join(__dirname, 'node_modules/redux')
},
extensions: ['', '.js']
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
query: {
plugins: ['react-transform'],
extra: {
'react-transform': {
transforms: [{
transform: 'react-transform-hmr',
imports: ['react'],
locals: ['module']
}, {
transform: 'react-transform-catch-errors',
imports: ['react', 'redbox-react']
}]
}
}
},
exclude: /node_modules/,
include: path.join(__dirname, 'src', 'javascript')
}, {
test: /\.css$/,
loaders: ['style', 'raw'],
include: __dirname
}, {
test: /\.less$/,
loaders: ['style', 'css', 'less'],
include: __dirname
}, {
test: /\.png$/,
loader: "url-loader?mimetype=image/png",
include: path.join(__dirname, 'src', 'images')
}, {
test: /\.woff|\.woff2$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.ttf$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
}, {
test: /\.eot$/,
loader: "file"
}, {
test: /\.svg$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
}]
}
};
================================================
FILE: webpack.config.production.js
================================================
/* eslint-disable */
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: './src/javascript/index',
output: {
path: path.join(__dirname, 'static'),
filename: 'bundle.js'
},
resolve: {
alias: {
'redux': path.join(__dirname, 'node_modules/redux')
},
extensions: [ '', '.js' ]
},
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
}),
new webpack.DefinePlugin({
__DEVELOPMENT__: false,
__DEVTOOLS__: false
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: path.join(__dirname, 'src', 'javascript')
}, {
test: /\.css$/,
loaders: ['style', 'raw'],
include: __dirname
}, {
test: /\.less$/,
loaders: ['style', 'css', 'less'],
include: __dirname
}, {
test: /\.png$/,
loader: "url-loader?mimetype=image/png",
include: path.join(__dirname, 'src', 'images')
}, {
test: /\.woff|\.woff2$/,
loader: "url?limit=10000&mimetype=application/font-woff"
}, {
test: /\.ttf$/,
loader: "url?limit=10000&mimetype=application/octet-stream"
}, {
test: /\.eot$/,
loader: "file"
}, {
test: /\.svg$/,
loader: "url?limit=10000&mimetype=image/svg+xml"
}]
}
};