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
================================================
<html>
<head>
<title>React Redux Boilerplate</title>
</head>
<body style="margin: 0; -webkit-font-smoothing: antialiased;">
<div id="root"></div>
</body>
<script src="./static/bundle.js"></script>
</html>
================================================
FILE: package.json
================================================
{
"name": "redux-blogapp",
"version": "0.0.1",
"description": "Redux and React Router Blogapp example",
"author": "Mateusz Zatorski <mateuszzatorski@gmail.com> (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 (
<div>
<Provider store={store}>
<Router history={createBrowserHistory()}>
<Route path='/' component={Blog} />
<Route path='/post/:id/edit' component={Draft} onEnter={hooks.editPost(store)}/>
<Route path='/post/new' component={Draft}/>
<Route path='/login' component={Login}/>
</Router>
</Provider>
<DevTools store={store} />
</div>
);
}
};
================================================
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 (
<div style={styles.layout}>
<div style={styles.footerText}>
Contribute to the
<a href='https://github.com/knowbody/redux-react-router-example-app'
target='_blank'
style={{textDecoration: 'none'}}> project on GitHub</a>.
</div>
</div>
);
}
}
================================================
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 = (
<div>
<a style={styles.link}
href='https://github.com/knowbody/redux-react-router-example-app'
target='_blank'>
<image style={styles.image} src={SocialGithub} />
</a>
<IconMenu style={styles.iconMenu}
iconButtonElement={
<IconButton>
<NavigationMoreVert color='white' />
</IconButton>
}>
<MenuItem leftIcon={<ActionAccountCicle />} primaryText='Login'
onTouchTap={() => history.pushState(null, '/login')} />
</IconMenu>
</div>
);
return (
<AppBar title='(redux, reactRouter) => example'
iconElementLeft={<span />}
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 (
<div>
<Header />
<main style={styles.main}>
{this.props.children}
<Footer />
</main>
</div>
);
}
}
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(
<DockMonitor toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'>
<LogMonitor theme='solarized' />
</DockMonitor>
);
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 <ComposedComponent {...other} />;
}
};
}
================================================
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(<Root />, 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=<key> 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=<key> 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 = <CardTitle title={post.title} subtitle={post.subtitle}/>;
if (post.poster) {
title = (
<CardMedia style={styles.cardMedia}
mediaStyle={styles.cardMediaStyle}
overlay={title}>
<div>
<img style={styles.cardMediaImage} src={post.poster}/>
</div>
</CardMedia>
);
}
return (
<Card style={styles.card}>
<CardHeader title={`${user.firstname} ${user.lastname}`}
avatar={user.avatar}>
<IconMenu style={styles.iconMenu}
iconButtonElement={
<IconButton><NavigationMoreVert /></IconButton>
}>
<MenuItem leftIcon={<EditorModeEdit />} primaryText='Edit'
onTouchTap={() => {
history.pushState(null, `/post/${post.id}/edit`);
}}/>
<MenuItem leftIcon={<ActionDelete />} primaryText='Remove'
onTouchTap={actions.removePost.bind(null, post)}/>
<MenuItem leftIcon={<SocialShare />} primaryText='Share'/>
</IconMenu>
</CardHeader>
{title}
{ post.body ? <CardText>{post.body}</CardText> : '' }
</Card>
);
}
}
================================================
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 (
<AppBar>
{blogposts.map((post, i) =>
<Post key={i}
post={post}
user={users.filter(user => user.id === post.user)[0]}
actions={actions}/>
)}
<FloatingActionButton style={styles.addContent}
onTouchTap={() => {
history.pushState(null, '/post/new');
}}>
<ContentAdd />
</FloatingActionButton>
</AppBar>
);
}
}
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 = (
<form style={styles.form}
onChange={({ target }) => {
updateDraft({ [target.name]: target.value });
}}
onSubmit={this.onSubmit.bind(this, actions, draft)}>
<TextField name='title'
style={styles.textField}
hintText='title'
floatingLabelText='title'
value={draft.title}/>
<TextField name='subtitle'
style={styles.textField}
hintText='subtitle'
floatingLabelText='subtitle'
value={draft.subtitle}/>
<TextField name='poster'
style={styles.textField}
hintText='poster url'
floatingLabelText='poster url'
value={draft.poster}/>
<TextField name='body' style={styles.textField}
hintText='whats this about...?'
floatingLabelText='whats this about...?'
value={draft.body}
multiLine />
<RaisedButton type='submit'
style={styles.submit}
label={isEdit ? 'Save' : 'Publish'}
primary />
<div style={{ clear: 'both' }}/>
</form>
);
return (
<AppBar>
<Paper style={styles.paper}>
{form}
</Paper>
</AppBar>
);
}
}
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 (
<div style={styles.center}>
<Paper style={styles.paper}>
<ActionAccountCicle style={{ height: 100, width: 100 }}/><br/>
<TextField ref='identity'
hintText='email'
floatingLabelText='email'
defaultValue='john.doe@example.com'
onKeyDown={::this.submit} /><br/>
<TextField ref='password'
hintText='password'
floatingLabelText='password'
type='password'
defaultValue='qwertyuiop'
onKeyDown={::this.submit} /><br />
<RaisedButton style={styles.submit}
label='Submit'
onTouchTap={::this.submit}
primary />
</Paper>
</div>
);
}
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"
}]
}
};
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
SYMBOL INDEX (76 symbols across 19 files)
FILE: src/javascript/Root.js
class Root (line 18) | class Root extends Component {
method render (line 19) | render() {
FILE: src/javascript/components/Footer.js
class Footer (line 15) | class Footer extends Component {
method render (line 16) | render() {
FILE: src/javascript/components/Header.js
class Header (line 11) | class Header extends Component {
method getStyles (line 16) | getStyles() {
method render (line 34) | render() {
FILE: src/javascript/containers/AppBar.js
class AppBar (line 6) | class AppBar extends Component {
method getStyles (line 15) | getStyles() {
method render (line 25) | render() {
FILE: src/javascript/decorators/withMaterialUI.js
function withMaterialUI (line 5) | function withMaterialUI(ComposedComponent) {
FILE: src/javascript/hooks.js
function bootstrap (line 5) | function bootstrap({ dispatch }) {
function editPost (line 15) | function editPost({ dispatch }) {
FILE: src/javascript/redux/index.js
function getDebugSessionKey (line 22) | function getDebugSessionKey() {
FILE: src/javascript/redux/middleware/clientMiddleware.js
function clientMiddleware (line 1) | function clientMiddleware(client) {
FILE: src/javascript/redux/middleware/logger.js
function logger (line 6) | function logger({ getState }) {
FILE: src/javascript/redux/middleware/request.js
function request (line 4) | function request({ dispatch }) {
FILE: src/javascript/redux/modules/auth.js
constant LOGIN (line 1) | const LOGIN = 'auth/LOGIN';
constant LOGIN_SUCCESS (line 2) | const LOGIN_SUCCESS = 'auth/LOGIN_SUCCESS';
constant LOGIN_FAILURE (line 3) | const LOGIN_FAILURE = 'auth/LOGIN_FAILURE';
constant REGISTER (line 5) | const REGISTER = 'auth/REGISTER';
constant REGISTER_SUCCESS (line 6) | const REGISTER_SUCCESS = 'auth/REGISTER_SUCCESS';
constant REGISTER_FAILURE (line 7) | const REGISTER_FAILURE = 'auth/REGISTER_FAILURE';
function reducer (line 21) | function reducer(state = initialState, action = {}) {
FILE: src/javascript/redux/modules/blogposts.js
constant FETCH_POSTS (line 1) | const FETCH_POSTS = 'blogposts/FETCH_POSTS';
constant FETCH_POSTS_SUCCESS (line 2) | const FETCH_POSTS_SUCCESS = 'blogposts/FETCH_POSTS_SUCCESS';
constant FETCH_POSTS_FAILURE (line 3) | const FETCH_POSTS_FAILURE = 'blogposts/FETCH_POSTS_FAILURE';
constant CREATE_POST (line 5) | const CREATE_POST = 'blogposts/CREATE_POST';
constant CREATE_POST_SUCCESS (line 6) | const CREATE_POST_SUCCESS = 'blogposts/CREATE_POST_SUCCESS';
constant CREATE_POST_FAILURE (line 7) | const CREATE_POST_FAILURE = 'blogposts/CREATE_POST_FAILURE';
constant READ_POST (line 9) | const READ_POST = 'blogposts/READ_POST';
constant READ_POST_SUCCESS (line 10) | const READ_POST_SUCCESS = 'blogposts/READ_POST_SUCCESS';
constant READ_POST_FAILURE (line 11) | const READ_POST_FAILURE = 'blogposts/READ_POST_FAILURE';
constant UPDATE_POST (line 13) | const UPDATE_POST = 'blogposts/UPDATE_POST';
constant UPDATE_POST_SUCCESS (line 14) | const UPDATE_POST_SUCCESS = 'blogposts/UPDATE_POST_SUCCESS';
constant UPDATE_POST_FAILURE (line 15) | const UPDATE_POST_FAILURE = 'blogposts/UPDATE_POST_FAILURE';
constant REMOVE_POST (line 17) | const REMOVE_POST = 'blogposts/REMOVE_POST';
constant REMOVE_POST_SUCCESS (line 18) | const REMOVE_POST_SUCCESS = 'blogposts/REMOVE_POST_SUCCESS';
constant REMOVE_POST_FAILURE (line 19) | const REMOVE_POST_FAILURE = 'blogposts/REMOVE_POST_FAILURE';
constant SET_DRAFT (line 21) | const SET_DRAFT = 'draft/SET_DRAFT';
constant UPDATE_DRAFT (line 22) | const UPDATE_DRAFT = 'draft/UPDATE_DRAFT';
function indexOfObjectById (line 26) | function indexOfObjectById(arr, obj) {
function reducer (line 32) | function reducer(state = initialState, action = {}) {
function fetchPosts (line 70) | function fetchPosts(start = 0, limit = 10) {
function createPost (line 81) | function createPost(post) {
function readPost (line 97) | function readPost(id) {
function updatePost (line 108) | function updatePost(post) {
function removePost (line 125) | function removePost(post) {
function setDraft (line 141) | function setDraft(postId) {
function updateDraft (line 161) | function updateDraft(draft) {
FILE: src/javascript/redux/modules/draft.js
constant CREATE_POST_SUCCESS (line 1) | const CREATE_POST_SUCCESS = 'draft/CREATE_POST_SUCCESS';
constant UPDATE_POST_SUCCESS (line 2) | const UPDATE_POST_SUCCESS = 'draft/UPDATE_POST_SUCCESS';
constant SET_DRAFT (line 4) | const SET_DRAFT = 'draft/SET_DRAFT';
constant UPDATE_DRAFT (line 5) | const UPDATE_DRAFT = 'draft/UPDATE_DRAFT';
function reducer (line 14) | function reducer(state = initialState, action = {}) {
FILE: src/javascript/redux/modules/users.js
constant FETCH_USERS (line 1) | const FETCH_USERS = 'users/FETCH_USERS';
function reducer (line 5) | function reducer(state = initialState, action = {}) {
function fetchUsers (line 20) | function fetchUsers() {
FILE: src/javascript/redux/modules/utils/fetch.js
function read (line 15) | function read(url) {
function create (line 28) | function create(url, body = {}) {
function update (line 42) | function update(url, body = {}) {
function destroy (line 56) | function destroy(url) {
FILE: src/javascript/views/Blog/Post.js
class Blogpost (line 17) | class Blogpost extends Component {
method getStyles (line 37) | getStyles() {
method render (line 66) | render() {
FILE: src/javascript/views/Blog/index.js
class BlogApp (line 10) | class BlogApp extends Component {
method getStyles (line 21) | getStyles() {
method render (line 32) | render() {
FILE: src/javascript/views/Draft/index.js
class Draft (line 8) | class Draft extends Component {
method onSubmit (line 19) | onSubmit(actions, payload) {
method getStyles (line 31) | getStyles() {
method render (line 49) | render() {
FILE: src/javascript/views/Login/index.js
class Login (line 9) | class Login extends Component {
method getStyles (line 18) | getStyles() {
method render (line 41) | render() {
method submit (line 68) | submit(event) {
Condensed preview — 43 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (47K chars).
[
{
"path": ".babelrc",
"chars": 19,
"preview": "{\n \"stage\": 0\n}\n"
},
{
"path": ".eslintignore",
"chars": 17,
"preview": "lib\nnode_modules\n"
},
{
"path": ".eslintrc",
"chars": 1188,
"preview": "{\n \"extends\": \"eslint-config-airbnb\",\n \"env\": {\n \"browser\": true,\n \"es6\": true,\n \"mocha\": true,\n \"node\": t"
},
{
"path": ".gitignore",
"chars": 49,
"preview": "node_modules\nnpm-debug.log\n.DS_Store\ndist\nstatic\n"
},
{
"path": ".travis.yml",
"chars": 38,
"preview": "language: node_js\nnode_js:\n - \"iojs\"\n"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 1423,
"preview": "# Contributor Code of Conduct\n\nAs contributors and maintainers of this project, we pledge to respect all people who cont"
},
{
"path": "LICENSE",
"chars": 1084,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2015 Mateusz Zatorski\n\nPermission is hereby granted, free of charge, to any person "
},
{
"path": "Procfile",
"chars": 20,
"preview": "web: npm run deploy\n"
},
{
"path": "README.md",
"chars": 892,
"preview": "Redux and React Router Example App\n===\n[;\nvar data = require('./test/fixture/data');\n\nvar server = "
},
{
"path": "index.html",
"chars": 223,
"preview": "<html>\n <head>\n <title>React Redux Boilerplate</title>\n </head>\n <body style=\"margin: 0; -webkit-font-smoothing: a"
},
{
"path": "package.json",
"chars": 2437,
"preview": "{\n \"name\": \"redux-blogapp\",\n \"version\": \"0.0.1\",\n \"description\": \"Redux and React Router Blogapp example\",\n \"author\""
},
{
"path": "server.js",
"chars": 1114,
"preview": "/* eslint-disable */\nvar isDev = (process.env.NODE_ENV !== 'production');\nvar webpack = require('webpack');\nvar express "
},
{
"path": "src/javascript/Root.js",
"chars": 1088,
"preview": "import React, { Component, PropTypes } from 'react';\nimport { Router, Route } from 'react-router';\nimport createBrowserH"
},
{
"path": "src/javascript/components/Footer.js",
"chars": 601,
"preview": "import React, { Component } from 'react';\n\nconst styles = {\n layout: {\n height: '100px'\n },\n\n footerText: {\n te"
},
{
"path": "src/javascript/components/Header.js",
"chars": 1843,
"preview": "import React, { PropTypes, Component } from 'react';\nimport { AppBar, IconButton, Styles } from 'material-ui';\nimport Ic"
},
{
"path": "src/javascript/config/urls.js",
"chars": 44,
"preview": "export const api = 'http://localhost:3010';\n"
},
{
"path": "src/javascript/containers/AppBar.js",
"chars": 779,
"preview": "import React, { Component, PropTypes } from 'react';\nimport { connect } from 'react-redux';\nimport Header from '../compo"
},
{
"path": "src/javascript/containers/DevTools.js",
"chars": 554,
"preview": "import React from 'react';\n\n// Exported from redux-devtools\nimport { createDevTools } from 'redux-devtools';\n\n// Monitor"
},
{
"path": "src/javascript/decorators/withMaterialUI.js",
"chars": 812,
"preview": "import React, { Component } from 'react';\nimport ThemeManager from 'material-ui/lib/styles/theme-manager';\nimport LightR"
},
{
"path": "src/javascript/hooks.js",
"chars": 604,
"preview": "import { bindActionCreators } from 'redux';\nimport * as UserActions from './redux/modules/users';\nimport * as BlogAction"
},
{
"path": "src/javascript/index.js",
"chars": 455,
"preview": "import 'babel/polyfill';\nimport React from 'react';\nimport { render } from 'react-dom';\nimport injectTapEventPlugin from"
},
{
"path": "src/javascript/redux/index.js",
"chars": 1039,
"preview": "import { createStore, applyMiddleware, compose } from 'redux';\nimport { devTools, persistState } from 'redux-devtools';\n"
},
{
"path": "src/javascript/redux/middleware/clientMiddleware.js",
"chars": 710,
"preview": "export default function clientMiddleware(client) {\n return ({dispatch, getState}) => {\n return next => action => {\n "
},
{
"path": "src/javascript/redux/middleware/index.js",
"chars": 147,
"preview": "import thunk from 'redux-thunk';\nimport logger from './logger';\nimport request from './request';\n\nexport default [\n thu"
},
{
"path": "src/javascript/redux/middleware/logger.js",
"chars": 374,
"preview": "/**\n * Logs previous and current state for every action call\n * @param getState\n * @returns {Function}\n */\nexport defaul"
},
{
"path": "src/javascript/redux/middleware/request.js",
"chars": 1066,
"preview": "import * as urls from '../../config/urls';\nimport { defaultParams as defaultFetchParams } from '../modules/utils/fetch';"
},
{
"path": "src/javascript/redux/modules/auth.js",
"chars": 1917,
"preview": "const LOGIN = 'auth/LOGIN';\nconst LOGIN_SUCCESS = 'auth/LOGIN_SUCCESS';\nconst LOGIN_FAILURE = 'auth/LOGIN_FAILURE';\n\ncon"
},
{
"path": "src/javascript/redux/modules/blogposts.js",
"chars": 4005,
"preview": "const FETCH_POSTS = 'blogposts/FETCH_POSTS';\nconst FETCH_POSTS_SUCCESS = 'blogposts/FETCH_POSTS_SUCCESS';\nconst FETCH_PO"
},
{
"path": "src/javascript/redux/modules/draft.js",
"chars": 925,
"preview": "const CREATE_POST_SUCCESS = 'draft/CREATE_POST_SUCCESS';\nconst UPDATE_POST_SUCCESS = 'draft/UPDATE_POST_SUCCESS';\n\nexpor"
},
{
"path": "src/javascript/redux/modules/reducer.js",
"chars": 294,
"preview": "import { combineReducers } from 'redux';\nimport { reducer as form } from 'redux-form';\n\nimport auth from './auth';\nimpor"
},
{
"path": "src/javascript/redux/modules/users.js",
"chars": 587,
"preview": "const FETCH_USERS = 'users/FETCH_USERS';\n\nconst initialState = [];\n\nexport default function reducer(state = initialState"
},
{
"path": "src/javascript/redux/modules/utils/fetch.js",
"chars": 988,
"preview": "export const defaultParams = {\n mode: 'cors',\n credentials: 'include',\n headers: {\n Accept: 'application/json',\n "
},
{
"path": "src/javascript/views/Blog/Post.js",
"chars": 3002,
"preview": "import React, { Component, PropTypes } from 'react';\nimport {\n Card,\n CardHeader,\n CardMedia,\n CardTitle,\n CardText"
},
{
"path": "src/javascript/views/Blog/index.js",
"chars": 1688,
"preview": "import React, { Component, PropTypes } from 'react';\nimport { bindActionCreators } from 'redux';\nimport { connect } from"
},
{
"path": "src/javascript/views/Draft/index.js",
"chars": 3008,
"preview": "import React, { Component, PropTypes } from 'react';\nimport { bindActionCreators } from 'redux';\nimport { connect } from"
},
{
"path": "src/javascript/views/Login/index.js",
"chars": 2304,
"preview": "import React, { PropTypes, Component } from 'react';\nimport { bindActionCreators } from 'redux';\nimport { connect } from"
},
{
"path": "src/styles/main.less",
"chars": 127,
"preview": "// Reset\n@import '~normalize.css/normalize.css';\n\n\n// Correct some stuff in scaffolding.less\nsvg {\n box-sizing: content"
},
{
"path": "test/fixture/data.js",
"chars": 1011,
"preview": "var casual = require('casual');\n\nvar arrayOf = function(times, type) {\n var result = [];\n\n for (var i = 0; i < times; "
},
{
"path": "test/index.spec.js",
"chars": 0,
"preview": ""
},
{
"path": "webpack.config.js",
"chars": 1877,
"preview": "/* eslint-disable */\nvar path = require('path');\nvar webpack = require('webpack');\n\nmodule.exports = {\n devtool: 'sourc"
},
{
"path": "webpack.config.production.js",
"chars": 1511,
"preview": "/* eslint-disable */\nvar path = require('path');\nvar webpack = require('webpack');\n\nmodule.exports = {\n devtool: 'sourc"
}
]
About this extraction
This page contains the full source code of the knowbody/redux-react-router-example-app GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 43 files (42.0 KB), approximately 11.6k tokens, and a symbol index with 76 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.