chore(extension): add extension (#658)

* Move extension

* prettier
This commit is contained in:
Nathan Bierema 2020-10-26 08:18:23 -04:00 committed by GitHub
parent 7ae485b035
commit 6782f4ae41
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
198 changed files with 23627 additions and 0 deletions

4
extension/.babelrc Normal file
View File

@ -0,0 +1,4 @@
{
"presets": ["es2015", "stage-0", "react"],
"plugins": ["add-module-exports", "transform-decorators-legacy"]
}

8
extension/.bookignore Normal file
View File

@ -0,0 +1,8 @@
src/
build/
dev/
examples/
npm-package/
test/
package.json
webpack/

8
extension/.eslintignore Normal file
View File

@ -0,0 +1,8 @@
node_modules
build
dev
webpack/replace
examples
test/app/setup.js
npm-package
_book

30
extension/.eslintrc Normal file
View File

@ -0,0 +1,30 @@
{
"extends": "eslint-config-airbnb",
"globals": {
"chrome": true,
"__DEVELOPMENT__": true
},
"env": {
"browser": true,
"node": true
},
"rules": {
"react/jsx-uses-react": 2,
"react/jsx-uses-vars": 2,
"react/react-in-jsx-scope": 2,
"react/jsx-quotes": 0,
"block-scoped-var": 0,
"padded-blocks": 0,
"quotes": [1, "single"],
"comma-style": [2, "last"],
"no-use-before-define": [0, "nofunc"],
"func-names": 0,
"prefer-const": 0,
"comma-dangle": 0,
"id-length": 0,
"indent": [2, 2, { "SwitchCase": 1 }],
"new-cap": [2, { "capIsNewExceptions": ["Test"] }],
"default-case": 0
},
"plugins": ["react"]
}

9
extension/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
node_modules
npm-debug.log
.DS_Store
.idea/
dist/
build/
dev/
tmp/
_book

32
extension/.travis.yml Normal file
View File

@ -0,0 +1,32 @@
sudo: required
dist: trusty
language: node_js
node_js:
- '6'
cache:
directories:
- $HOME/.yarn-cache
- node_modules
env:
- CXX=g++-4.8
addons:
apt:
sources:
- google-chrome
- ubuntu-toolchain-r-test
packages:
- google-chrome-stable
- g++-4.8
install:
- '/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -ac -screen 0 1280x1024x16'
- npm install -g yarn
- yarn install
before_script:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start &
- sleep 3
script:
- yarn test

4
extension/CHANGELOG.md Normal file
View File

@ -0,0 +1,4 @@
# Change Log
This project adheres to [Semantic Versioning](http://semver.org/).
Every release, along with the migration instructions, is documented on the Github [Releases](https://github.com/zalmoxisus/redux-devtools-extension/releases) page.

View File

@ -0,0 +1,63 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
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, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

21
extension/LICENSE Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015-present Mihail Diordiev
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.

325
extension/README.md Normal file
View File

@ -0,0 +1,325 @@
# Redux DevTools Extension
[![Join the chat at https://gitter.im/zalmoxisus/redux-devtools-extension](https://badges.gitter.im/zalmoxisus/redux-devtools-extension.svg)](https://gitter.im/zalmoxisus/redux-devtools-extension?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=round-square)](http://makeapullrequest.com)
[![OpenCollective](https://opencollective.com/redux-devtools-extension/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/redux-devtools-extension/sponsors/badge.svg)](#sponsors)
![Demo](https://cloud.githubusercontent.com/assets/7957859/18002950/aacb82fc-6b93-11e6-9ae9-609862c18302.png)
## Installation
### 1. For Chrome
- from [Chrome Web Store](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd);
- or download `extension.zip` from [last releases](https://github.com/zalmoxisus/redux-devtools-extension/releases), unzip, open `chrome://extensions` url and turn on developer mode from top left and then click; on `Load Unpacked` and select the extracted folder for use
- or build it with `npm i && npm run build:extension` and [load the extension's folder](https://developer.chrome.com/extensions/getstarted#unpacked) `./build/extension`;
- or run it in dev mode with `npm i && npm start` and [load the extension's folder](https://developer.chrome.com/extensions/getstarted#unpacked) `./dev`.
### 2. For Firefox
- from [Mozilla Add-ons](https://addons.mozilla.org/en-US/firefox/addon/reduxdevtools/);
- or build it with `npm i && npm run build:firefox` and [load the extension's folder](https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Temporary_Installation_in_Firefox) `./build/firefox` (just select a file from inside the dir).
### 3. For Electron
- just specify `REDUX_DEVTOOLS` in [`electron-devtools-installer`](https://github.com/GPMDP/electron-devtools-installer).
### 4. For other browsers and non-browser environment
- use [`remote-redux-devtools`](https://github.com/zalmoxisus/remote-redux-devtools).
## Usage
> Note that starting from v2.7, `window.devToolsExtension` was renamed to `window.__REDUX_DEVTOOLS_EXTENSION__` / `window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__`.
## 1. With Redux
### 1.1 Basic store
For a basic [Redux store](https://redux.js.org/api/createstore#createstorereducer-preloadedstate-enhancer) simply add:
```diff
const store = createStore(
reducer, /* preloadedState, */
+ window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
```
Note that [`preloadedState`](https://redux.js.org/api/createstore#createstorereducer-preloadedstate-enhancer) argument is optional in Redux's [`createStore`](https://redux.js.org/api/createstore#createstorereducer-preloadedstate-enhancer).
> For universal ("isomorphic") apps, prefix it with `typeof window !== 'undefined' &&`.
```js
const composeEnhancers =
(typeof window !== 'undefined' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
compose;
```
> For TypeScript use [`redux-devtools-extension` npm package](#13-use-redux-devtools-extension-package-from-npm), which contains all the definitions, or just use `(window as any)` (see [Recipes](/docs/Recipes.md#using-in-a-typescript-project) for an example).
```js
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
```
In case ESLint is configured to not allow using the underscore dangle, wrap it like so:
```diff
+ /* eslint-disable no-underscore-dangle */
const store = createStore(
reducer, /* preloadedState, */
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
+ /* eslint-enable */
```
> **Note**: Passing enhancer as last argument requires **redux@>=3.1.0**. For older versions apply it like [here](https://github.com/zalmoxisus/redux-devtools-extension/blob/v0.4.2/examples/todomvc/store/configureStore.js) or [here](https://github.com/zalmoxisus/redux-devtools-extension/blob/v0.4.2/examples/counter/store/configureStore.js#L7-L12). Don't mix the old Redux API with the new one.
> You don't need to npm install [`redux-devtools`](https://github.com/gaearon/redux-devtools) when using the extension (that's a different lib).
### 1.2 Advanced store setup
If you setup your store with [middleware and enhancers](http://redux.js.org/docs/api/applyMiddleware.html), change:
```diff
import { createStore, applyMiddleware, compose } from 'redux';
+ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
+ const store = createStore(reducer, /* preloadedState, */ composeEnhancers(
- const store = createStore(reducer, /* preloadedState, */ compose(
applyMiddleware(...middleware)
));
```
> Note that when the extension is not installed, were using Redux compose here.
To specify [extensions options](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Arguments.md), use it like so:
```js
const composeEnhancers =
typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// Specify extensions options like name, actionsBlacklist, actionsCreators, serialize...
})
: compose;
const enhancer = composeEnhancers(
applyMiddleware(...middleware)
// other store enhancers if any
);
const store = createStore(reducer, enhancer);
```
> [See the post for more details](https://medium.com/@zalmoxis/improve-your-development-workflow-with-redux-devtools-extension-f0379227ff83).
### 1.3 Use `redux-devtools-extension` package from npm
To make things easier, there's an npm package to install:
```
npm install --save redux-devtools-extension
```
and to use like so:
```js
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
const store = createStore(
reducer,
composeWithDevTools(
applyMiddleware(...middleware)
// other store enhancers if any
)
);
```
To specify [extensions options](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Arguments.md#windowdevtoolsextensionconfig):
```js
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
const composeEnhancers = composeWithDevTools({
// Specify name here, actionsBlacklist, actionsCreators and other options if needed
});
const store = createStore(
reducer,
/* preloadedState, */ composeEnhancers(
applyMiddleware(...middleware)
// other store enhancers if any
)
);
```
> Therere just [few lines of code](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/npm-package/index.js) added to your bundle.
In case you don't include other enhancers and middlewares, just use `devToolsEnhancer`:
```js
import { createStore } from 'redux';
import { devToolsEnhancer } from 'redux-devtools-extension';
const store = createStore(
reducer,
/* preloadedState, */ devToolsEnhancer()
// Specify name here, actionsBlacklist, actionsCreators and other options if needed
);
```
### 1.4 Using in production
It's useful to include the extension in production as well. Usually you [can use it for development](https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f).
If you want to restrict it there, use `redux-devtools-extension/logOnlyInProduction`:
```js
import { createStore } from 'redux';
import { devToolsEnhancer } from 'redux-devtools-extension/logOnlyInProduction';
const store = createStore(
reducer,
/* preloadedState, */ devToolsEnhancer()
// options like actionSanitizer, stateSanitizer
);
```
or with middlewares and enhancers:
```js
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension/logOnlyInProduction';
const composeEnhancers = composeWithDevTools({
// options like actionSanitizer, stateSanitizer
});
const store = createStore(
reducer,
/* preloadedState, */ composeEnhancers(
applyMiddleware(...middleware)
// other store enhancers if any
)
);
```
> You'll have to add `'process.env.NODE_ENV': JSON.stringify('production')` in your Webpack config for the production bundle ([to envify](https://github.com/gaearon/redux-devtools/blob/master/docs/Walkthrough.md#exclude-devtools-from-production-builds)). If you use `create-react-app`, [it already does it for you.](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/webpack.config.prod.js#L253-L257)
If you're already checking `process.env.NODE_ENV` when creating the store, include `redux-devtools-extension/logOnly` for production environment.
If you dont want to allow the extension in production, just use `redux-devtools-extension/developmentOnly`.
> See [the article](https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f) for more details.
### 1.5 For React Native, hybrid, desktop and server side Redux apps
For React Native we can use [`react-native-debugger`](https://github.com/jhen0409/react-native-debugger), which already included [the same API](https://github.com/jhen0409/react-native-debugger/blob/master/docs/redux-devtools-integration.md) with Redux DevTools Extension.
For most platforms, include [`Remote Redux DevTools`](https://github.com/zalmoxisus/remote-redux-devtools)'s store enhancer, and from the extension's context menu choose 'Open Remote DevTools' for remote monitoring.
## 2. Without Redux
See [integrations](docs/Integrations.md) and [the blog post](https://medium.com/@zalmoxis/redux-devtools-without-redux-or-how-to-have-a-predictable-state-with-any-architecture-61c5f5a7716f) for more details on how to use the extension with any architecture.
## Docs
- [Options (arguments)](docs/API/Arguments.md)
- [Methods (advanced API)](docs/API/Methods.md)
- [FAQ](docs/FAQ.md)
- Features
- [Trace actions calls](/docs/Features/Trace.md)
- [Troubleshooting](docs/Troubleshooting.md)
- [Articles](docs/Articles.md)
- [Videos](docs/Videos.md)
- [Feedback](docs/Feedback.md)
## Demo
Live demos to use the extension with:
- [Counter](http://zalmoxisus.github.io/examples/counter/)
- [TodoMVC](http://zalmoxisus.github.io/examples/todomvc/)
- [Redux Form](http://redux-form.com/6.5.0/examples/simple/)
- [React Tetris](https://chvin.github.io/react-tetris/?lan=en)
- [Book Collection (Angular ngrx store)](https://ngrx.github.io/platform/example-app/)
Also see [`./examples` folder](https://github.com/zalmoxisus/redux-devtools-extension/tree/master/examples).
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/redux-devtools-extension#backer)]
<a href="https://opencollective.com/redux-devtools-extension/backer/0/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/1/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/2/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/3/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/4/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/5/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/6/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/7/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/8/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/9/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/10/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/11/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/12/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/13/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/14/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/15/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/16/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/17/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/18/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/19/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/20/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/21/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/22/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/23/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/24/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/25/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/26/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/27/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/28/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/backer/29/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/redux-devtools-extension#sponsor)]
<a href="https://opencollective.com/redux-devtools-extension/sponsor/0/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/1/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/2/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/3/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/4/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/5/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/6/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/7/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/8/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/9/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/10/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/11/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/12/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/13/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/14/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/15/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/16/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/17/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/18/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/19/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/20/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/21/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/22/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/23/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/24/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/25/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/26/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/27/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/28/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/redux-devtools-extension/sponsor/29/website" target="_blank"><img src="https://opencollective.com/redux-devtools-extension/sponsor/29/avatar.svg"></a>
## License
MIT
## Created By
If you like this, follow [@mdiordiev](https://twitter.com/mdiordiev) on twitter.

1
extension/SUMMARY.md Normal file
View File

@ -0,0 +1 @@
./docs/README.md

18
extension/appveyor.yml Normal file
View File

@ -0,0 +1,18 @@
environment:
matrix:
- nodejs_version: '6'
cache:
- '%LOCALAPPDATA%/Yarn'
- node_modules
install:
- ps: Install-Product node $env:nodejs_version
- yarn install
test_script:
- node --version
- yarn --version
- yarn test
build: off

18
extension/book.json Normal file
View File

@ -0,0 +1,18 @@
{
"gitbook": "3.2.2",
"title": "Redux DevTools Extension",
"plugins": ["edit-link", "prism", "-highlight", "github", "anchorjs"],
"pluginsConfig": {
"edit-link": {
"base": "https://github.com/zalmoxisus/redux-devtools-extension/tree/master",
"label": "Edit This Page"
},
"github": {
"url": "https://github.com/zalmoxisus/redux-devtools-extension/"
},
"sharing": {
"facebook": true,
"twitter": true
}
}
}

View File

@ -0,0 +1,324 @@
# Options
Use with
- `window.__REDUX_DEVTOOLS_EXTENSION__([options])`
- `window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__([options])()`
- `window.__REDUX_DEVTOOLS_EXTENSION__.connect([options])`
- `redux-devtools-extension` npm package:
```js
import { composeWithDevTools } from 'redux-devtools-extension';
const composeEnhancers = composeWithDevTools(options);
const store = createStore(
reducer,
/* preloadedState, */ composeEnhancers(
applyMiddleware(...middleware)
// other store enhancers if any
)
);
```
The `options` object is optional, and can include any of the following.
### `name`
_string_ - the instance name to be shown on the monitor page. Default value is `document.title`. If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
### `actionCreators`
_array_ or _object_ - action creators functions to be available in the Dispatcher. See [the example](https://github.com/zalmoxisus/redux-devtools-extension/commit/477e69d8649dfcdc9bf84dd45605dab7d9775c03).
### `latency`
_number (in ms)_ - if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once. It is the joint between performance and speed. When set to `0`, all actions will be sent instantly. Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value). Default is `500 ms`.
### `maxAge`
_number_ (>1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance. Default is `50`.
### `trace`
_boolean_ or _function_ - if set to `true`, will include stack trace for every dispatched action, so you can see it in trace tab jumping directly to that part of code ([more details](../Features/Trace.md)). You can use a function (with action object as argument) which should return `new Error().stack` string, getting the stack outside of reducers. Default to `false`.
### `traceLimit`
_number_ - maximum stack trace frames to be stored (in case `trace` option was provided as `true`). By default it's `10`. Note that, because extension's calls are excluded, the resulted frames could be 1 less. If `trace` option is a function, `traceLimit` will have no effect, as it's supposed to be handled there.
### `serialize`
_boolean_ or _object_ which contains:
- **options** `object or boolean`:
- `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
- `false` - will handle also circular references.
- `true` - will handle also date, regex, undefined, primitives, error objects, symbols, maps, sets and functions.
- object, which contains `date`, `regex`, `undefined`, `nan`, `infinity`, `error`, `symbol`, `map`, `set` and `function` keys. For each of them you can indicate if to include (by setting as `true`). For `function` key you can also specify a custom function which handles serialization. See [`jsan`](https://github.com/kolodny/jsan) for more details. Example:
```js
const store = Redux.createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
serialize: {
options: {
undefined: true,
function: function (fn) {
return fn.toString();
},
},
},
})
);
```
- **replacer** `function(key, value)` - [JSON `replacer` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
Example of usage with [mori data structures](https://github.com/swannodette/mori):
```js
const store = Redux.createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
serialize: {
replacer: (key, value) =>
value && mori.isMap(value) ? mori.toJs(value) : value,
},
})
);
```
In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4) key. So you can deserialize it back while importing or persisting data. Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
```js
const store = Redux.createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
serialize: {
replacer: (key, value) => {
if (Immutable.List.isList(value)) {
// use your custom data type checker
return {
data: value.toArray(), // ImmutableJS custom method to get JS data as array
__serializedType__: 'ImmutableList', // mark you custom data type to show and retrieve back
};
}
},
},
})
);
```
- **reviver** `function(key, value)` - [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter) used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41) as an example on how to serialize special data types and get them back:
```js
const store = Redux.createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
serialize: {
reviver: (key, value) => {
if (
typeof value === 'object' &&
value !== null &&
'__serializedType__' in value
) {
switch (value.__serializedType__) {
case 'ImmutableList':
return Immutable.List(value.data);
}
}
},
},
})
);
```
- **immutable** `object` - automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize). Just pass the Immutable library like so:
```js
import Immutable from 'immutable'; // https://facebook.github.io/immutable-js/
// ...
// Like above, only showing off compose this time. Reminder you might not want this in prod.
const composeEnhancers =
typeof window === 'object' &&
typeof window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ !== 'undefined'
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
serialize: {
immutable: Immutable,
},
})
: compose;
```
It will support all ImmutableJS structures. You can even export them into a file and get them back. The only exception is `Record` class, for which you should pass in addition the references to your classes in `refs`.
- **refs** `array` - ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting... Example of usage:
```js
import Immutable from 'immutable';
// ...
const ABRecord = Immutable.Record({ a: 1, b: 2 });
const myRecord = new ABRecord({ b: 3 }); // used in the reducers
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
serialize: {
immutable: Immutable,
refs: [ABRecord],
},
})
);
```
Also you can specify alternative values right in the state object (in the initial state of the reducer) by adding `toJSON` function:
In the example bellow it will always send `{ component: '[React]' }`, regardless of the state's `component` value (useful when you don't want to send lots of unnecessary data):
```js
function component(
state = { component: null, toJSON: () => ({ component: '[React]' }) },
action
) {
switch (action.type) {
case 'ADD_COMPONENT':
return { component: action.component };
default:
return state;
}
}
```
You could also alter the value. For example when state is `{ count: 1 }`, we'll send `{ counter: 10 }` (notice we don't have an arrow function this time to use the object's `this`):
```js
function counter(
state = {
count: 0,
toJSON: function () {
return { conter: this.count * 10 };
},
},
action
) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
}
```
### `actionSanitizer` / `stateSanitizer`
- **actionSanitizer** (_function_) - function which takes `action` object and id number as arguments, and should return `action` object back. See the example bellow.
- **stateSanitizer** (_function_) - function which takes `state` object and index as arguments, and should return `state` object back.
Example of usage:
```js
const actionSanitizer = (action) =>
action.type === 'FILE_DOWNLOAD_SUCCESS' && action.data
? { ...action, data: '<<LONG_BLOB>>' }
: action;
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
actionSanitizer,
stateSanitizer: (state) =>
state.data ? { ...state, data: '<<LONG_BLOB>>' } : state,
})
);
```
### `actionsBlacklist` / `actionsWhitelist`
_string or array of strings as regex_ - actions types to be hidden / shown in the monitors (while passed to the reducers). If `actionsWhitelist` specified, `actionsBlacklist` is ignored.
Example:
```js
createStore(
reducer,
remotedev({
sendTo: 'http://localhost:8000',
actionsBlacklist: 'SOME_ACTION',
// or actionsBlacklist: ['SOME_ACTION', 'SOME_OTHER_ACTION']
// or just actionsBlacklist: 'SOME_' to omit both
})
);
```
### `predicate`
_function_ - called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor. Use it as a more advanced version of `actionsBlacklist`/`actionsWhitelist` parameters.
Example of usage:
```js
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
predicate: (state, action) =>
state.dev.logLevel === VERBOSE && !action.forwarded,
})
);
```
### `shouldRecordChanges`
_boolean_ - if specified as `false`, it will not record the changes till clicking on `Start recording` button. Default is `true`. Available only for Redux enhancer, for others use `autoPause`.
### `pauseActionType`
_string_ - if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type. If not specified, will commit when paused. Available only for Redux enhancer. Default is `@@PAUSED`.
### `autoPause`
_boolean_ - auto pauses when the extensions window is not opened, and so has zero impact on your app when not in use. Not available for Redux enhancer (as it already does it but storing the data to be sent). Default is `false`.
### `shouldStartLocked`
_boolean_ - if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button. Available only for Redux enhancer. Default is `false`.
### `shouldHotReload`
_boolean_ - if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer. Default to `true`.
### `shouldCatchErrors`
_boolean_ - if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
### `features`
If you want to restrict the extension, just specify the features you allow:
```js
const composeEnhancers = composeWithDevTools({
features: {
pause: true, // start/pause recording of dispatched actions
lock: true, // lock/unlock dispatching actions and side effects
persist: true, // persist states on page reloading
export: true, // export history of actions in a file
import: 'custom', // import history of actions from a file
jump: true, // jump back and forth (time travelling)
skip: true, // skip (cancel) actions
reorder: true, // drag and drop actions in the history list
dispatch: true, // dispatch custom actions or action creators
test: true, // generate tests for the selected actions
},
// other options like actionSanitizer, stateSanitizer
});
```
If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side. Otherwise, you'll get/set the data right from the monitor part.

View File

@ -0,0 +1,93 @@
## Communicate with the extension directly
> Note this is advanced API, which you usually don't need to use with Redux enhancer.
Use the following methods of `window.__REDUX_DEVTOOLS_EXTENSION__`:
- [connect](#connect)
- [disconnect](#disconnect)
- [send](#send)
- [listen](#listen)
- [open](#open)
- [notifyErrors](#notifyerrors)
<a id="connect"></a>
### connect([options])
##### Arguments
- [`options`] _Object_ - [see the available options](Arguments.md).
##### Returns
_Object_ containing the following methods:
- `subscribe(listener)` - adds a change listener. It will be called any time an action is dispatched from the monitor. Returns a function to unsubscribe the current listener.
- `unsubscribe()` - unsubscribes all listeners.
- `send(action, state)` - sends a new action and state manually to be shown on the monitor. If action is `null` then we suppose we send `liftedState`.
- `init(state)` - sends the initial state to the monitor.
- `error(message)` - sends the error message to be shown in the extension's monitor.
Example of usage:
```js
const devTools = window.__REDUX_DEVTOOLS_EXTENSION__.connect(config);
devTools.subscribe((message) => {
if (message.type === 'DISPATCH' && message.state) {
console.log('DevTools requested to change the state to', message.state);
}
});
devTools.init({ value: 'initial state' });
devTools.send('change state', { value: 'state changed' });
```
See [redux enhancer's example](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/npm-package/logOnly.js), [react example](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/examples/react-counter-messaging/components/Counter.js) and [blog post](https://medium.com/@zalmoxis/redux-devtools-without-redux-or-how-to-have-a-predictable-state-with-any-architecture-61c5f5a7716f) for more details.
### disconnect()
Remove extensions listener and disconnect extensions background script connection. Usually just unsubscribing the listener inside the `connect` is enough.
<a id="send"></a>
### send(action, state, [options, instanceId])
Send a new action and state manually to be shown on the monitor. It's recommended to use [`connect`](connect), unless you want to hook into an already created instance.
##### Arguments
- `action` _String_ (action type) or _Object_ with required `type` key.
- `state` _any_ - usually object to expand.
- [`options`] _Object_ - [see the available options](Arguments.md).
- [`instanceId`] _String_ - instance id for which to include the log. If not specified and not present in the `options` object, will be the first available instance.
<a id="listen"></a>
### listen(onMessage, instanceId)
Listen for messages dispatched for specific `instanceId`. For most cases it's better to use `subcribe` inside the [`connect`](connect).
##### Arguments
- `onMessage` _Function_ to call when there's an action from the monitor.
- `instanceId` _String_ - instance id for which to handle actions.
<a id="open"></a>
### open([position])
Open the extension's window. This should be conditional (usually you don't need to open extension's window automatically).
##### Arguments
- [`position`] _String_ - window position: `left`, `right`, `bottom`. Also can be `panel` to [open it in a Chrome panel](../FAQ.md#how-to-keep-devtools-window-focused-all-the-time-in-a-chrome-panel). Or `remote` to [open remote monitor](../FAQ.md#how-to-get-it-work-with-webworkers-react-native-hybrid-desktop-and-server-side-apps). By default is `left`.
<a id="notifyErrors"></a>
### notifyErrors([onError])
When called, the extension will listen for uncaught exceptions on the page, and, if any, will show native notifications. Optionally, you can provide a function to be called when an exception occurs.
##### Arguments
- [`onError`] _Function_ to call when there's an exceptions.

View File

@ -0,0 +1,4 @@
# API Reference
- [Parameters](Arguments.md)
- [Methods](Methods.md)

View File

@ -0,0 +1,5 @@
# Articles
- [Improve your development workflow with Redux DevTools Extension](https://medium.com/@zalmoxis/improve-your-development-workflow-with-redux-devtools-extension-f0379227ff83)
- [Using Redux DevTools in production](https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f)
- [Redux DevTools without Redux](https://medium.com/@zalmoxis/redux-devtools-without-redux-or-how-to-have-a-predictable-state-with-any-architecture-61c5f5a7716f)

11
extension/docs/Credits.md Normal file
View File

@ -0,0 +1,11 @@
# Credits
- Built using [Crossbuilder](https://github.com/zalmoxisus/crossbuilder) boilerplate.
- Includes [Dan Abramov](https://github.com/gaearon)'s [redux-devtools](https://github.com/gaearon/redux-devtools) and the following monitors:
- [Log Monitor](https://github.com/gaearon/redux-devtools-log-monitor)
- [Inspector](https://github.com/alexkuz/redux-devtools-inspector)
- [Dispatch](https://github.com/YoruNoHikage/redux-devtools-dispatch)
- [Slider](https://github.com/calesce/redux-slider-monitor)
- [Chart](https://github.com/romseguy/redux-devtools-chart-monitor)
- [The logo icon](https://github.com/reactjs/redux/issues/151) made by [Keith Yong](https://github.com/keithyong) .
- Examples from [Redux](https://github.com/rackt/redux/tree/master/examples).

45
extension/docs/FAQ.md Normal file
View File

@ -0,0 +1,45 @@
# Redux DevTools Extension FAQ
## Table of Contents
- [How to get it work](#how-to-get-it-work)
- [How to disable/enable it in production](#how-to-disable-it-in-production)
- [How to persist debug sessions across page reloads](#how-to-persist-debug-sessions-across-page-reloads)
- [How to open DevTools programmatically](#how-to-open-devtools-programmatically)
- [How to enable/disable errors notifying](#how-to-enabledisable-errors-notifying)
- [How to get it work with WebWorkers, React Native, hybrid, desktop and server side apps](#how-to-get-it-work-with-webworkers-react-native-hybrid-desktop-and-server-side-apps)
- [Keyboard shortcuts](#keyboard-shortcuts)
#### How to get it work
- Check the extension with [Counter](http://zalmoxisus.github.io/examples/counter/) or [TodoMVC](http://zalmoxisus.github.io/examples/todomvc/) demo.
- Reload the extension on the extensions page (`chrome://extensions/`).
- If something goes wrong, [open an issue](https://github.com/zalmoxisus/redux-devtools-extension/issues) or tweet me: [@mdiordiev](https://twitter.com/mdiordiev).
#### How to disable it in production
Usually you don't have to. See [the article for details on how to include it in production](https://medium.com/@zalmoxis/using-redux-devtools-in-production-4c5b56c5600f).
#### How to persist debug sessions across page reloads
Just click the `Persist` button or add `?debug_session=<session_name>` to the url.
#### How to open DevTools programmatically
```js
window.__REDUX_DEVTOOLS_EXTENSION__.open();
```
Make sure to have it conditionally. Auto opening windows is a bad DX. See the [API](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Methods.md#open) for details.
#### How to enable/disable errors notifying
Just find `Redux DevTools` on the extensions page (`chrome://extensions/`) and click the `Options` link to customize everything. The errors notifying is disabled by default. If enabled, it works only when the store enhancer is called (in order not to show notifications for any sites you visit). In case you want notifications for a non-redux app, init it explicitly by calling `window.__REDUX_DEVTOOLS_EXTENSION__.notifyErrors()` (probably you'll check if `window.__REDUX_DEVTOOLS_EXTENSION__` exists before calling it).
#### How to get it work with WebWorkers, React Native, hybrid, desktop and server side apps
It is not possible to inject extension's script there and to communicate directly. To solve this, use [Remote Redux DevTools](https://github.com/zalmoxisus/remote-redux-devtools). After including it inside the app, click `Remote` button for remote monitoring.
#### Keyboard shortcuts
To set/change the keyboard shortcuts, click "Keyboard shortcuts" button on the bottom of the extensions page (`chrome://extensions/`). By default only `Cmd` (`Ctrl`) + `Shift` + `E` is available, which will open the extension popup (only when the Redux store is available in the current page).

View File

@ -0,0 +1,13 @@
## Trace actions calls
![trace-demo](https://user-images.githubusercontent.com/7957859/50161148-a1639300-02e3-11e9-80e7-18d3215a0bf8.gif)
One of the features of Redux DevTools is to select an action in the history and see the callstack that triggered it. It aims to solve the problem of finding the source of events in the event list.
By default it's disabled as, depending of the use case, generating and serializing stack traces for every action can impact the performance. To enable it, set `trace` option to `true` as in [examples](https://github.com/zalmoxisus/redux-devtools-extension/commit/64717bb9b3534ff616d9db56c2be680627c7b09d). See [the API](../API/Arguments.md#trace) for more details.
For some edge cases where stack trace cannot be obtained with just `Error().stack`, you can pass a function as `trace` with your implementation. It's useful for cases where the stack is broken, like, for example, [when calling `setTimeout`](https://github.com/zalmoxisus/redux-devtools-instrument/blob/e7c05c98e7e9654cb7db92a2f56c6b5f3ff2452b/test/instrument.spec.js#L735-L737). It takes `action` object as argument and should return `stack` string. This way it can be also used to provide stack conditionally only for certain actions.
There's also an optional `traceLimit` parameter, which is `10` by default, to prevent consuming too much memory and serializing large stacks and also allows you to get larger stacks than limited by the browser (it will overpass default limit of `10` imposed by Chrome in `Error.stackTraceLimit`). If `trace` option is a function, `traceLimit` will have no effect, that should be handled there like so: `trace: () => new Error().stack.split('\n').slice(0, limit+1).join('\n')` (`+1` is needed for Chrome where's an extra 1st frame for `Error\n`).
Apart from opening resources in Chrome DevTools, as seen in the demo above, it can open the file (and jump to the line-column) right in your editor. Pretty useful for debugging, and also as an alternative when it's not possible to use openResource (for Firefox or when using the extension from window or for remote debugging). You can click Settings button and enable that, also adding the path to your project root directory to use. It works out of the box for VSCode, Atom, Webstorm/Phpstorm/IntelliJ, Sublime, Emacs, MacVim, Textmate on Mac and Windows. For Linux you can use [`atom-url-handler`](https://github.com/eclemens/atom-url-handler).

View File

@ -0,0 +1,5 @@
# Feedback wanted
[File an issue](https://github.com/zalmoxisus/redux-devtools-extension/issues) or [submit a PR](https://github.com/zalmoxisus/redux-devtools-extension/pulls) if you have suggestions, rate us and leave a review on [Chrome Store](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd/reviews), post feature requests and bug reports on [Product Pains](https://productpains.com/product/redux-devtools-extension), or ping me on Twitter as [@mdiordiev](https://twitter.com/mdiordiev).
<iframe width="100%" height="400px" scrolling="no" style="border:0" src="https://productpains.com/widget.html?token=fc7887ce-f3f9-105a-e5cb-43b9eeb668d5"></iframe><script type="text/javascript" src="https://productpains.com/js/lib/iframeResizer.min.js"></script>

View File

@ -0,0 +1,302 @@
# Integrations for js and non-js frameworks
Mostly functional:
- [React](#react)
- [Angular](#angular)
- [Cycle](#cycle)
- [Ember](#ember)
- [Fable](#fable)
- [Freezer](#freezer)
- [Mobx](#mobx)
- [PureScript](#purescript)
- [Reductive](#reductive)
- [Aurelia](#aurelia)
In progress:
- [ClojureScript](#clojurescript)
- [Horizon](#horizon)
- [Python](#python)
- [Swift](#swift)
### [React](https://github.com/facebook/react)
#### Inspect React props
##### [`react-inspect-props`](https://github.com/lucasconstantino/react-inspect-props)
```js
import { compose, withState } from 'recompose';
import { inspectProps } from 'react-inspect-props';
compose(
withState('count', 'setCount', 0),
inspectProps('Counter inspector')
)(Counter);
```
#### Inspect React states
##### [`remotedev-react-state`](https://github.com/jhen0409/remotedev-react-state)
```js
import connectToDevTools from 'remotedev-react-state'
componentWillMount() {
// Connect to devtools after setup initial state
connectToDevTools(this/*, options */)
}
```
#### Inspect React hooks (useState and useReducer)
##### [`reinspect`](https://github.com/troch/reinspect)
```js
import { useState } from 'reinspect';
export function CounterWithUseState({ id }) {
const [count, setCount] = useState(0, id);
// ...
}
```
### [Mobx](https://github.com/mobxjs/mobx)
#### [`mobx-remotedev`](https://github.com/zalmoxisus/mobx-remotedev)
```js
import remotedev from 'mobx-remotedev';
// or import remotedev from 'mobx-remotedev/lib/dev'
// in case you want to use it in production or don't have process.env.NODE_ENV === 'development'
const appStore = observable({
// ...
});
// Or
class appStore {
// ...
}
export default remotedev(appStore);
```
### [Angular](https://github.com/angular/angular)
#### [ng2-redux](https://github.com/angular-redux/ng2-redux)
```js
import { NgReduxModule, NgRedux, DevToolsExtension } from 'ng2-redux';
@NgModule({
/* ... */
imports: [ /* ... */, NgReduxModule ]
})export class AppModule {
constructor(
private ngRedux: NgRedux,
private devTools: DevToolsExtension) {
let enhancers = [];
// ... add whatever other enhancers you want.
// You probably only want to expose this tool in devMode.
if (__DEVMODE__ && devTools.isEnabled()) {
enhancers = [ ...enhancers, devTools.enhancer() ];
}
this.ngRedux.configureStore(
rootReducer,
initialState,
[],
enhancers);
}
}
```
For Angular 1 see [ng-redux](https://github.com/angular-redux/ng-redux).
#### [Angular @ngrx/store](https://ngrx.io/) + [`@ngrx/store-devtools`](https://ngrx.io/guide/store-devtools)
```js
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
@NgModule({
imports: [
StoreModule.forRoot(rootReducer),
// Instrumentation must be imported after importing StoreModule (config is optional)
StoreDevtoolsModule.instrument({
maxAge: 5,
}),
],
})
export class AppModule {}
```
[`Example of integration`](https://github.com/ngrx/platform/tree/master/projects/example-app/) ([live demo](https://ngrx.github.io/platform/example-app/)).
### [Ember](http://emberjs.com/)
#### [`ember-redux`](https://github.com/ember-redux/ember-redux)
```js
//app/enhancers/index.js
import { compose } from 'redux';
var devtools = window.__REDUX_DEVTOOLS_EXTENSION__
? window.__REDUX_DEVTOOLS_EXTENSION__()
: (f) => f;
export default compose(devtools);
```
### [Cycle](https://github.com/cyclejs/cyclejs)
#### [`@culli/store`](https://github.com/milankinen/culli/tree/master/packages/store)
```js
import { run } from '@cycle/most-run';
import { makeDOMDriver as DOM } from '@cycle/dom';
import Store, { ReduxDevtools } from '@culli/store';
import App, { newId } from './App';
run(App, {
DOM: DOM('#app'),
Store: Store(
ReduxDevtools({
items: [
{ id: newId(), num: 0 },
{ id: newId(), num: 0 },
],
})
),
});
```
### [Freezer](https://github.com/arqex/freezer)
#### [`freezer-redux-devtools`](https://github.com/arqex/freezer-redux-devtools)
```js
import React, { Component } from 'react';
import { supportChromeExtension } from 'freezer-redux-devtools/freezer-redux-middleware';
import Freezer from 'freezer-js';
// Our state is a freezer object
var State = new Freezer({ hello: 'world' });
// Enable the extension
supportChromeExtension(State);
```
### [Horizon](https://github.com/rethinkdb/horizon)
#### [`horizon-remotedev`](https://github.com/zalmoxisus/horizon-remotedev)
```js
// import hzRemotedev from 'horizon-remotedev';
// or import hzRemotedev from 'horizon-remotedev/lib/dev'
// in case you want to use it in production or don't have process.env.NODE_ENV === 'development'
//Setup Horizon connection
const horizon = Horizon();
// ...
// Specify the horizon instance to monitor
hzRemotedev(horizon('react_messages'));
```
### [Fable](https://github.com/fable-compiler/Fable)
#### [`fable-elmish/debugger`](https://github.com/fable-elmish/debugger)
```fsharp
open Elmish.Debug
Program.mkProgram init update view
|> Program.withDebugger // connect to a devtools monitor via Chrome extension if available
|> Program.run
```
or
```fsharp
open Elmish.Debug
Program.mkProgram init update view
|> Program.withDebuggerAt (Remote("localhost",8000)) // connect to a server running on localhost:8000
|> Program.run
```
### [PureScript](https://github.com/purescript/purescript)
#### [`purescript-react-redux`](https://github.com/ethul/purescript-react-redux)
[`Example of integration`](https://github.com/ethul/purescript-react-redux-example).
### [ClojureScript](https://github.com/clojure/clojurescript)
[`Example of integration`](http://gitlab.xet.ru:9999/publicpr/clojurescript-redux/tree/master#dev-setup)
### [Python](https://www.python.org/)
#### [`pyredux`](https://github.com/peterpeter5/pyredux)
[WIP](https://github.com/zalmoxisus/remotedev-server/issues/34)
### [Swift](https://github.com/apple/swift)
#### [`katanaMonitor`](https://github.com/bolismauro/katanaMonitor-lib-swift) for [`katana-swift`](https://github.com/BendingSpoons/katana-swift)
```swift
import KatanaMonitor
var middleware: [StoreMiddleware] = [
// other middleware
]
#if DEBUG
middleware.append(MonitorMiddleware.create(using: .defaultConfiguration))
#endif
```
### [Reductive](https://github.com/reasonml-community/reductive)
#### [`reductive-dev-tools`](https://github.com/ambientlight/reductive-dev-tools)
```reason
let storeEnhancer =
ReductiveDevTools.(
Connectors.reductiveEnhancer(
Extension.enhancerOptions(~name="MyApp", ()),
)
);
let storeCreator = storeEnhancer @@ Reductive.Store.create;
```
### [Aurelia](http://aurelia.io)
#### [`aurelia-store`](https://aurelia.io/docs/plugins/store)
```ts
import {Aurelia} from 'aurelia-framework';
import {initialState} from './state';
export function configure(aurelia: Aurelia) {
aurelia.use
.standardConfiguration()
.feature('resources');
...
aurelia.use.plugin('aurelia-store', {
initialState,
devToolsOptions: { // optional
... // see https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Arguments.md
},
});
aurelia.start().then(() => aurelia.setRoot());
}
```

21
extension/docs/README.md Normal file
View File

@ -0,0 +1,21 @@
# Documentation
- [Extension](/README.md)
- [Installation](/README.md#installation)
- [Usage](/README.md#usage)
- [Demo](/README.md#demo)
- [API Reference](/docs/API/README.md)
- [Options (arguments)](/docs/API/Arguments.md)
- [Methods (advanced API)](/docs/API/Methods.md)
- Features
- [Trace actions calls](/docs/Features/Trace.md)
- [Integrations](/docs/Integrations.md)
- [FAQ](/docs/FAQ.md)
- [Troubleshooting](/docs/Troubleshooting.md)
- [Recipes](/docs/Recipes.md)
- [Articles](/docs/Articles.md)
- [Videos](/docs/Videos.md)
- [Credits](/docs/Credits.md)
- [Support us](/README.md#backers)
- [Feedback](/docs/Feedback.md)
- [Change Log](https://github.com/zalmoxisus/redux-devtools-extension/releases)

78
extension/docs/Recipes.md Normal file
View File

@ -0,0 +1,78 @@
# Recipes
### Using in a typescript project
The recommended way is to use [`redux-devtools-extension` npm package](/README.md#13-use-redux-devtools-extension-package-from-npm), which contains all typescript definitions. Or you can just use `window as any`:
```js
const store = createStore(
rootReducer,
initialState,
(window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
(window as any).__REDUX_DEVTOOLS_EXTENSION__()
);
```
Note that you many need to set `no-any` to false in your `tslint.json` file.
Alternatively you can use typeguard in order to avoid
casting to any.
```typescript
import { createStore, StoreEnhancer } from 'redux';
// ...
type WindowWithDevTools = Window & {
__REDUX_DEVTOOLS_EXTENSION__: () => StoreEnhancer<unknown, {}>;
};
const isReduxDevtoolsExtenstionExist = (
arg: Window | WindowWithDevTools
): arg is WindowWithDevTools => {
return '__REDUX_DEVTOOLS_EXTENSION__' in arg;
};
// ...
const store = createStore(
rootReducer,
initialState,
isReduxDevtoolsExtenstionExist(window)
? window.__REDUX_DEVTOOLS_EXTENSION__()
: undefined
);
```
### Export from browser console or from application
```js
store.liftedStore.getState();
```
The extension is not sharing `store` object, so you should take care of that.
### Applying multiple times with different sets of options
We're [not allowing that from instrumentation part](https://github.com/zalmoxisus/redux-devtools-instrument/blob/master/src/instrument.js#L676), because that would re-dispatch every app action in case we'd have many liftedStores, but there's [a helper for logging only](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/npm-package/logOnly.js), which can be used it like so:
```js
import { createStore, compose } from 'redux';
import { devToolsEnhancer } from 'redux-devtools-extension/logOnly';
const store = createStore(
reducer,
/* preloadedState, */ compose(
devToolsEnhancer({
instaceID: 1,
name: 'Blacklisted',
actionsBlacklist: '...',
}),
devToolsEnhancer({
instaceID: 2,
name: 'Whitelisted',
actionsWhitelist: '...',
})
)
);
```

View File

@ -0,0 +1,129 @@
# Troubleshooting
### I just see empty log or "No store found"
Make sure you [applied the enhancer](https://github.com/zalmoxisus/redux-devtools-extension#2-use-with-redux). Note that passing enhancer as last argument requires redux@>=3.1.0. For older versions apply it like [here](https://github.com/zalmoxisus/redux-devtools-extension/blob/v0.4.2/examples/todomvc/store/configureStore.js) or [here](https://github.com/zalmoxisus/redux-devtools-extension/blob/v0.4.2/examples/counter/store/configureStore.js#L7-L12).
Don't mix the old Redux API with the new one. Pass enhancers and applyMiddleware as last createStore argument.
### Access file url (`file:///`)
If you develop on your local filesystem, make sure to allow Redux DevTools access to `file:///` URLs in the settings of this extension:
<img width="746" alt="extensions" src="https://cloud.githubusercontent.com/assets/7957859/19075220/a0fad99e-8a4c-11e6-8b87-757f2dc179cb.png">
### It shows only the `@@INIT` action or moving back and forth doesn't update the state
Most likely you mutate the state. Check it by [adding `redux-immutable-state-invariant` middleware](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/examples/counter/store/configureStore.js#L3).
### @@INIT or REPLACE action resets the state of the app or last actions RE-APPLIED
`@@redux/REPLACE` (or `@@INIT`) is used internally when the application is hot reloaded. When you use `store.replaceReducer` the effect will be the same as for hot-reloading, where the extension is recomputing all the history again. To avoid that set [`shouldHotReload`](/docs/API/Arguments.md#shouldhotreload) parameter to `false`.
### It doesn't work with other store enhancers
Usually the extension's store enhancer should be last in the compose. When you're using [`window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__`](/README.md#12-advanced-store-setup) or [`composeWithDevTools`](/README.md#13-use-redux-devtools-extension-package-from-npm) helper you don't have to worry about the enhancers order. However some enhancers ([like `redux-batched-subscribe`](https://github.com/zalmoxisus/redux-devtools-extension/issues/261)) also have this requirement to be the last in the compose. In this case you can use it like so:
```js
const store = createStore(
reducer,
preloadedState,
compose(
// applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__
? window.__REDUX_DEVTOOLS_EXTENSION__()
: (noop) => noop,
batchedSubscribe(/* ... */)
)
);
```
Where `batchedSubscribe` is `redux-batched-subscribe` store enhancer.
### Excessive use of memory and CPU
That is happening due to serialization of some huge objects included in the state or action. The solution is to [sanitize them](/docs/API/Arguments.md#actionsanitizer--statesanitizer).
You can do that by including/omitting data containing specific values, having specific types... In the example below we're omitting parts of action and state objects with the key `data` (in case of action only when was dispatched action `FILE_DOWNLOAD_SUCCESS`):
```js
const actionSanitizer = (action) =>
action.type === 'FILE_DOWNLOAD_SUCCESS' && action.data
? { ...action, data: '<<LONG_BLOB>>' }
: action;
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
actionSanitizer,
stateSanitizer: (state) =>
state.data ? { ...state, data: '<<LONG_BLOB>>' } : state,
})
);
```
There's a more advanced [example on how to implement that for `ui-router`](https://github.com/zalmoxisus/redux-devtools-extension/issues/455#issuecomment-404538385).
The extension is in different process and cannot access the store object directly, unlike vanilla [`redux-devtools`](https://github.com/reduxjs/redux-devtools) which doesn't have this issue. In case sanitizing doesn't fit your use case, you might consider including it directly as a react component, so there will be no need to serialize the data, but it would add some complexity.
### It fails to serialize data when [passing synthetic events](https://github.com/zalmoxisus/redux-devtools-extension/issues/275) or [calling an action directly with `redux-actions`](https://github.com/zalmoxisus/redux-devtools-extension/issues/287)
React synthetic event cannot be reused for performance reason. So, it's not possible to serialize event objects you pass to action payloads.
1. The best solution is **not to pass the whole event object to reducers, but the data you need**:
```diff
function click(event) {
return {
type: ELEMENT_CLICKED,
- event: event
+ value: event.target.value
};
}
```
2. If you cannot pick data from the event object or, for some reason, you need the whole object, use `event.persist()` as suggested in [React Docs](https://facebook.github.io/react/docs/events.html#event-pooling), but it will consume RAM while not needed.
```diff
function increment(event) {
+ event.persist();
return {
type: ELEMENT_CLICKED,
event: event,
};
}
```
3. A workaround, to pass the whole object and at the same time not to persist it, is to override this key of the stringified payload in your action creator. Add a custom `toJSON` function right in the action object (which will be called by the extension before accessing the object):
```diff
function increment(event) {
return {
type: ELEMENT_CLICKED,
event: event,
+ toJSON: function (){
+ return { ...this, event: '[Event]' };
+ }
};
}
```
Note that it shouldn't be arrow function as we want to have access to the function's `this`.
As we don't have access to the original object, skipping and recomputing actions during hot reloading will not work in this case. We recommend to use the first solution whenever possible.
### Symbols or other unserializable data not shown
To get data which cannot be serialized by `JSON.stringify`, set [`serialize` parameter](/docs/API/Arguments.md#serialize):
```js
const store = Redux.createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__({
serialize: true,
})
);
```
It will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.

6
extension/docs/Videos.md Normal file
View File

@ -0,0 +1,6 @@
# Videos
- [Debugging flux applications in production at React Europe 2016](https://youtu.be/YU8jQ2HtqH4)
- [Hot Reloading with Time Travel at React Europe 2015](https://youtu.be/xsSnOQynTHs)
- [Getting Started with Redux DevTools Extension](https://egghead.io/lessons/javascript-getting-started-with-redux-dev-tools)
- [React & Redux With ExpressJS](https://www.youtube.com/watch?v=6ygcbRpZFR4)

View File

@ -0,0 +1,36 @@
/**
* Runs an ordered set of commands within each of the build directories.
*/
import fs from 'fs';
import path from 'path';
import { spawnSync } from 'child_process';
var exampleDirs = fs.readdirSync(__dirname).filter((file) => {
return fs.statSync(path.join(__dirname, file)).isDirectory();
});
// Ordering is important here. `npm install` must come first.
var cmdArgs = [
{ cmd: 'npm', args: ['install'] },
{ cmd: 'webpack', args: ['index.js'] },
];
for (const dir of exampleDirs) {
for (const cmdArg of cmdArgs) {
// declare opts in this scope to avoid https://github.com/joyent/node/issues/9158
const opts = {
cwd: path.join(__dirname, dir),
stdio: 'inherit',
};
let result = {};
if (process.platform === 'win32') {
result = spawnSync(cmdArg.cmd + '.cmd', cmdArg.args, opts);
} else {
result = spawnSync(cmdArg.cmd, cmdArg.args, opts);
}
if (result.status !== 0) {
throw new Error('Building examples exited with non-zero');
}
}
}

View File

@ -0,0 +1,3 @@
{
"presets": ["es2015", "stage-0", "react"]
}

View File

@ -0,0 +1,37 @@
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER';
let t;
export function increment() {
return {
type: INCREMENT_COUNTER,
};
}
export function decrement() {
return {
type: DECREMENT_COUNTER,
};
}
export function autoIncrement(delay = 10) {
return (dispatch) => {
if (t) {
clearInterval(t);
t = undefined;
return;
}
t = setInterval(() => {
dispatch(increment());
}, delay);
};
}
export function incrementAsync(delay = 1000) {
return (dispatch) => {
setTimeout(() => {
dispatch(increment());
}, delay);
};
}

View File

@ -0,0 +1,32 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Counter extends Component {
render() {
const {
increment,
autoIncrement,
incrementAsync,
decrement,
counter,
} = this.props;
return (
<p>
Clicked: {counter} times <button onClick={increment}>+</button>{' '}
<button onClick={decrement}>-</button>{' '}
<button onClick={incrementAsync}>Increment async</button>{' '}
<button onClick={autoIncrement}>Auto increment</button>
</p>
);
}
}
Counter.propTypes = {
increment: PropTypes.func.isRequired,
autoIncrement: PropTypes.func.isRequired,
incrementAsync: PropTypes.func.isRequired,
decrement: PropTypes.func.isRequired,
counter: PropTypes.number.isRequired,
};
export default Counter;

View File

@ -0,0 +1,16 @@
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/counter';
function mapStateToProps(state) {
return {
counter: state.counter,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(CounterActions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Redux counter example</title>
</head>
<body>
<div id="root"></div>
<script src="/static/bundle.js"></script>
</body>
</html>

View File

@ -0,0 +1,14 @@
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);

View File

@ -0,0 +1,41 @@
{
"name": "redux-counter-example",
"version": "0.0.0",
"description": "Redux counter example",
"scripts": {
"start": "node server.js",
"test": "NODE_ENV=test mocha --recursive --compilers js:babel-core/register --require ./test/setup.js",
"test:watch": "npm test -- --watch"
},
"repository": {
"type": "git",
"url": "https://github.com/rackt/redux.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/rackt/redux/issues"
},
"homepage": "http://rackt.github.io/redux",
"dependencies": {
"prop-types": "^15.6.2",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-redux": "^6.0.0",
"redux": "^4.0.1",
"redux-devtools-extension": "^2.13.7",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"babel-cli": "^6.3.17",
"babel-core": "^6.3.17",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.0.0",
"babel-preset-react": "6.3.13",
"babel-preset-stage-0": "^6.3.13",
"express": "^4.13.3",
"redux-immutable-state-invariant": "^2.1.0",
"webpack": "^4.0.0",
"webpack-dev-server": "^3.0.0",
"webpack-hot-middleware": "^2.2.0"
}
}

View File

@ -0,0 +1,12 @@
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions/counter';
export default function counter(state = 0, action) {
switch (action.type) {
case INCREMENT_COUNTER:
return state + 1;
case DECREMENT_COUNTER:
return state - 1;
default:
return state;
}
}

View File

@ -0,0 +1,8 @@
import { combineReducers } from 'redux';
import counter from './counter';
const rootReducer = combineReducers({
counter,
});
export default rootReducer;

View File

@ -0,0 +1,32 @@
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var config = require('./webpack.config');
var app = new require('express')();
var port = 4001;
var compiler = webpack(config);
app.use(
webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
})
);
app.use(webpackHotMiddleware(compiler));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.listen(port, function (error) {
if (error) {
console.error(error);
} else {
console.info(
'==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.',
port,
port
);
}
});

View File

@ -0,0 +1,28 @@
import { createStore, applyMiddleware, compose } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import invariant from 'redux-immutable-state-invariant';
import reducer from '../reducers';
import * as actionCreators from '../actions/counter';
export default function configureStore(preloadedState) {
const composeEnhancers = composeWithDevTools({
actionCreators,
trace: true,
traceLimit: 25,
});
const store = createStore(
reducer,
preloadedState,
composeEnhancers(applyMiddleware(invariant(), thunk))
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
store.replaceReducer(require('../reducers').default);
});
}
return store;
}

View File

@ -0,0 +1,73 @@
import expect from 'expect';
import { applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import * as actions from '../../actions/counter';
const middlewares = [thunk];
/*
* Creates a mock of Redux store with middleware.
*/
function mockStore(getState, expectedActions, onLastAction) {
if (!Array.isArray(expectedActions)) {
throw new Error('expectedActions should be an array of expected actions.');
}
if (
typeof onLastAction !== 'undefined' &&
typeof onLastAction !== 'function'
) {
throw new Error('onLastAction should either be undefined or function.');
}
function mockStoreWithoutMiddleware() {
return {
getState() {
return typeof getState === 'function' ? getState() : getState;
},
dispatch(action) {
const expectedAction = expectedActions.shift();
expect(action).toEqual(expectedAction);
if (onLastAction && !expectedActions.length) {
onLastAction();
}
return action;
},
};
}
const mockStoreWithMiddleware = applyMiddleware(...middlewares)(
mockStoreWithoutMiddleware
);
return mockStoreWithMiddleware();
}
describe('actions', () => {
it('increment should create increment action', () => {
expect(actions.increment()).toEqual({ type: actions.INCREMENT_COUNTER });
});
it('decrement should create decrement action', () => {
expect(actions.decrement()).toEqual({ type: actions.DECREMENT_COUNTER });
});
it('incrementIfOdd should create increment action', (done) => {
const expectedActions = [{ type: actions.INCREMENT_COUNTER }];
const store = mockStore({ counter: 1 }, expectedActions, done);
store.dispatch(actions.incrementIfOdd());
});
it('incrementIfOdd shouldnt create increment action if counter is even', (done) => {
const expectedActions = [];
const store = mockStore({ counter: 2 }, expectedActions);
store.dispatch(actions.incrementIfOdd());
done();
});
it('incrementAsync should create increment action', (done) => {
const expectedActions = [{ type: actions.INCREMENT_COUNTER }];
const store = mockStore({ counter: 0 }, expectedActions, done);
store.dispatch(actions.incrementAsync(100));
});
});

View File

@ -0,0 +1,53 @@
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import Counter from '../../components/Counter';
function setup() {
const actions = {
increment: expect.createSpy(),
incrementIfOdd: expect.createSpy(),
incrementAsync: expect.createSpy(),
decrement: expect.createSpy(),
};
const component = TestUtils.renderIntoDocument(
<Counter counter={1} {...actions} />
);
return {
component: component,
actions: actions,
buttons: TestUtils.scryRenderedDOMComponentsWithTag(component, 'button'),
p: TestUtils.findRenderedDOMComponentWithTag(component, 'p'),
};
}
describe('Counter component', () => {
it('should display count', () => {
const { p } = setup();
expect(p.textContent).toMatch(/^Clicked: 1 times/);
});
it('first button should call increment', () => {
const { buttons, actions } = setup();
TestUtils.Simulate.click(buttons[0]);
expect(actions.increment).toHaveBeenCalled();
});
it('second button should call decrement', () => {
const { buttons, actions } = setup();
TestUtils.Simulate.click(buttons[1]);
expect(actions.decrement).toHaveBeenCalled();
});
it('third button should call incrementIfOdd', () => {
const { buttons, actions } = setup();
TestUtils.Simulate.click(buttons[2]);
expect(actions.incrementIfOdd).toHaveBeenCalled();
});
it('fourth button should call incrementAsync', () => {
const { buttons, actions } = setup();
TestUtils.Simulate.click(buttons[3]);
expect(actions.incrementAsync).toHaveBeenCalled();
});
});

View File

@ -0,0 +1,53 @@
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { Provider } from 'react-redux';
import App from '../../containers/App';
import configureStore from '../../store/configureStore';
function setup(initialState) {
const store = configureStore(initialState);
const app = TestUtils.renderIntoDocument(
<Provider store={store}>
<App />
</Provider>
);
return {
app: app,
buttons: TestUtils.scryRenderedDOMComponentsWithTag(app, 'button'),
p: TestUtils.findRenderedDOMComponentWithTag(app, 'p'),
};
}
describe('containers', () => {
describe('App', () => {
it('should display initial count', () => {
const { p } = setup();
expect(p.textContent).toMatch(/^Clicked: 0 times/);
});
it('should display updated count after increment button click', () => {
const { buttons, p } = setup();
TestUtils.Simulate.click(buttons[0]);
expect(p.textContent).toMatch(/^Clicked: 1 times/);
});
it('should display updated count after decrement button click', () => {
const { buttons, p } = setup();
TestUtils.Simulate.click(buttons[1]);
expect(p.textContent).toMatch(/^Clicked: -1 times/);
});
it('shouldnt change if even and if odd button clicked', () => {
const { buttons, p } = setup();
TestUtils.Simulate.click(buttons[2]);
expect(p.textContent).toMatch(/^Clicked: 0 times/);
});
it('should change if odd and if odd button clicked', () => {
const { buttons, p } = setup({ counter: 1 });
TestUtils.Simulate.click(buttons[2]);
expect(p.textContent).toMatch(/^Clicked: 2 times/);
});
});
});

View File

@ -0,0 +1,23 @@
import expect from 'expect';
import counter from '../../reducers/counter';
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../../actions/counter';
describe('reducers', () => {
describe('counter', () => {
it('should handle initial state', () => {
expect(counter(undefined, {})).toBe(0);
});
it('should handle INCREMENT_COUNTER', () => {
expect(counter(1, { type: INCREMENT_COUNTER })).toBe(2);
});
it('should handle DECREMENT_COUNTER', () => {
expect(counter(1, { type: DECREMENT_COUNTER })).toBe(0);
});
it('should handle unknown action type', () => {
expect(counter(1, { type: 'unknown' })).toBe(1);
});
});
});

View File

@ -0,0 +1,5 @@
import { jsdom } from 'jsdom';
global.document = jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = global.window.navigator;

View File

@ -0,0 +1,23 @@
var path = require('path');
var webpack = require('webpack');
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: ['webpack-hot-middleware/client', './index'],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
plugins: [new webpack.HotModuleReplacementPlugin()],
module: {
rules: [
{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: /node_modules/,
},
],
},
};

View File

@ -0,0 +1,3 @@
{
"presets": ["es2015", "stage-0", "react"]
}

View File

@ -0,0 +1,62 @@
import React, { Component } from 'react';
const withDevTools =
// process.env.NODE_ENV === 'development' &&
typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__;
class Counter extends Component {
constructor() {
super();
this.state = { counter: 0 };
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
}
componentWillMount() {
if (withDevTools) {
this.devTools = window.__REDUX_DEVTOOLS_EXTENSION__.connect();
this.unsubscribe = this.devTools.subscribe((message) => {
// Implement monitors actions.
// For example time traveling:
if (
message.type === 'DISPATCH' &&
message.payload.type === 'JUMP_TO_STATE'
) {
this.setState(message.state);
}
});
}
}
componentWillUnmount() {
if (withDevTools) {
this.unsubscribe(); // Use if you have other subscribers from other components.
window.__REDUX_DEVTOOLS_EXTENSION__.disconnect(); // If there aren't other subscribers.
}
}
increment() {
const state = { counter: this.state.counter + 1 };
if (withDevTools) this.devTools.send('increment', state);
this.setState(state);
}
decrement() {
const state = { counter: this.state.counter - 1 };
if (withDevTools) this.devTools.send('decrement', state);
this.setState(state);
}
render() {
const { counter } = this.state;
return (
<p>
Clicked: {counter} times <button onClick={this.increment}>+</button>{' '}
<button onClick={this.decrement}>-</button>
</p>
);
}
}
export default Counter;

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>React counter example</title>
</head>
<body>
<div id="root"></div>
<script src="/static/bundle.js"></script>
</body>
</html>

View File

@ -0,0 +1,5 @@
import React from 'react';
import { render } from 'react-dom';
import Counter from './components/Counter';
render(<Counter />, document.getElementById('root'));

View File

@ -0,0 +1,33 @@
{
"name": "react-counter-example",
"version": "0.0.0",
"description": "React counter example",
"scripts": {
"start": "webpack-dev-server --progress"
},
"repository": {
"type": "git",
"url": "https://github.com/zalmoxisus/redux-devtools-extension.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/zalmoxisus/redux-devtools-extension/issues"
},
"homepage": "https://github.com/zalmoxisus/redux-devtools-extension",
"dependencies": {
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"devDependencies": {
"babel-cli": "^6.3.17",
"babel-core": "^6.3.17",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.0.0",
"babel-preset-react": "6.3.13",
"babel-preset-stage-0": "^6.3.13",
"webpack": "^4.0.0",
"webpack-cli": "^3.2.0",
"webpack-dev-server": "^3.0.0",
"webpack-hot-middleware": "^2.2.0"
}
}

View File

@ -0,0 +1,25 @@
var path = require('path');
var webpack = require('webpack');
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: ['./index'],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
module: {
rules: [
{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: /node_modules/,
},
],
},
devServer: {
port: 4004,
},
};

View File

@ -0,0 +1,4 @@
{
"presets": ["es2015", "stage-0", "react"],
"plugins": ["add-module-exports", "transform-decorators-legacy"]
}

View File

@ -0,0 +1,25 @@
import * as types from '../constants/ActionTypes';
export function addTodo(text) {
return { type: types.ADD_TODO, text };
}
export function deleteTodo(id) {
return { type: types.DELETE_TODO, id };
}
export function editTodo(id, text) {
return { type: types.EDIT_TODO, id, text };
}
export function completeTodo(id) {
return { type: types.COMPLETE_TODO, id };
}
export function completeAll() {
return { type: types.COMPLETE_ALL };
}
export function clearCompleted() {
return { type: types.CLEAR_COMPLETED };
}

View File

@ -0,0 +1,76 @@
import React, { PropTypes, Component } from 'react';
import classnames from 'classnames';
import {
SHOW_ALL,
SHOW_COMPLETED,
SHOW_ACTIVE,
} from '../constants/TodoFilters';
const FILTER_TITLES = {
[SHOW_ALL]: 'All',
[SHOW_ACTIVE]: 'Active',
[SHOW_COMPLETED]: 'Completed',
};
class Footer extends Component {
renderTodoCount() {
const { activeCount } = this.props;
const itemWord = activeCount === 1 ? 'item' : 'items';
return (
<span className="todo-count">
<strong>{activeCount || 'No'}</strong> {itemWord} left
</span>
);
}
renderFilterLink(filter) {
const title = FILTER_TITLES[filter];
const { filter: selectedFilter, onShow } = this.props;
return (
<a
className={classnames({ selected: filter === selectedFilter })}
style={{ cursor: 'pointer' }}
onClick={() => onShow(filter)}
>
{title}
</a>
);
}
renderClearButton() {
const { completedCount, onClearCompleted } = this.props;
if (completedCount > 0) {
return (
<button className="clear-completed" onClick={onClearCompleted}>
Clear completed
</button>
);
}
}
render() {
return (
<footer className="footer">
{this.renderTodoCount()}
<ul className="filters">
{[SHOW_ALL, SHOW_ACTIVE, SHOW_COMPLETED].map((filter) => (
<li key={filter}>{this.renderFilterLink(filter)}</li>
))}
</ul>
{this.renderClearButton()}
</footer>
);
}
}
Footer.propTypes = {
completedCount: PropTypes.number.isRequired,
activeCount: PropTypes.number.isRequired,
filter: PropTypes.string.isRequired,
onClearCompleted: PropTypes.func.isRequired,
onShow: PropTypes.func.isRequired,
};
export default Footer;

View File

@ -0,0 +1,30 @@
import React, { PropTypes, Component } from 'react';
import TodoTextInput from './TodoTextInput';
class Header extends Component {
handleSave(text) {
if (text.length !== 0) {
this.props.addTodo(text);
}
}
render() {
const { path } = this.props;
return (
<header className="header">
<h1 style={{ fontSize: 80 }}>{path}</h1>
<TodoTextInput
newTodo
onSave={this.handleSave.bind(this)}
placeholder="What needs to be done?"
/>
</header>
);
}
}
Header.propTypes = {
addTodo: PropTypes.func.isRequired,
};
export default Header;

View File

@ -0,0 +1,94 @@
import React, { Component, PropTypes } from 'react';
import TodoItem from './TodoItem';
import Footer from './Footer';
import {
SHOW_ALL,
SHOW_COMPLETED,
SHOW_ACTIVE,
} from '../constants/TodoFilters';
const TODO_FILTERS = {
[SHOW_ALL]: () => true,
[SHOW_ACTIVE]: (todo) => !todo.completed,
[SHOW_COMPLETED]: (todo) => todo.completed,
};
class MainSection extends Component {
constructor(props, context) {
super(props, context);
this.state = { filter: SHOW_ALL };
}
handleClearCompleted() {
const atLeastOneCompleted = this.props.todos.some((todo) => todo.completed);
if (atLeastOneCompleted) {
this.props.actions.clearCompleted();
}
}
handleShow(filter) {
this.setState({ filter });
}
renderToggleAll(completedCount) {
const { todos, actions } = this.props;
if (todos.length > 0) {
return (
<input
className="toggle-all"
type="checkbox"
checked={completedCount === todos.length}
onChange={actions.completeAll}
/>
);
}
}
renderFooter(completedCount) {
const { todos } = this.props;
const { filter } = this.state;
const activeCount = todos.length - completedCount;
if (todos.length) {
return (
<Footer
completedCount={completedCount}
activeCount={activeCount}
filter={filter}
onClearCompleted={this.handleClearCompleted.bind(this)}
onShow={this.handleShow.bind(this)}
/>
);
}
}
render() {
const { todos, actions } = this.props;
const { filter } = this.state;
const filteredTodos = todos.filter(TODO_FILTERS[filter]);
const completedCount = todos.reduce(
(count, todo) => (todo.completed ? count + 1 : count),
0
);
return (
<section className="main">
{this.renderToggleAll(completedCount)}
<ul className="todo-list">
{filteredTodos.map((todo) => (
<TodoItem key={todo.id} todo={todo} {...actions} />
))}
</ul>
{this.renderFooter(completedCount)}
</section>
);
}
}
MainSection.propTypes = {
todos: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
export default MainSection;

View File

@ -0,0 +1,75 @@
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import TodoTextInput from './TodoTextInput';
class TodoItem extends Component {
constructor(props, context) {
super(props, context);
this.state = {
editing: false,
};
}
handleDoubleClick() {
this.setState({ editing: true });
}
handleSave(id, text) {
if (text.length === 0) {
this.props.deleteTodo(id);
} else {
this.props.editTodo(id, text);
}
this.setState({ editing: false });
}
render() {
const { todo, completeTodo, deleteTodo } = this.props;
let element;
if (this.state.editing) {
element = (
<TodoTextInput
text={todo.text}
editing={this.state.editing}
onSave={(text) => this.handleSave(todo.id, text)}
/>
);
} else {
element = (
<div className="view">
<input
className="toggle"
type="checkbox"
checked={todo.completed}
onChange={() => completeTodo(todo.id)}
/>
<label onDoubleClick={this.handleDoubleClick.bind(this)}>
{todo.text}
</label>
<button className="destroy" onClick={() => deleteTodo(todo.id)} />
</div>
);
}
return (
<li
className={classnames({
completed: todo.completed,
editing: this.state.editing,
})}
>
{element}
</li>
);
}
}
TodoItem.propTypes = {
todo: PropTypes.object.isRequired,
editTodo: PropTypes.func.isRequired,
deleteTodo: PropTypes.func.isRequired,
completeTodo: PropTypes.func.isRequired,
};
export default TodoItem;

View File

@ -0,0 +1,59 @@
import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
class TodoTextInput extends Component {
constructor(props, context) {
super(props, context);
this.state = {
text: this.props.text || '',
};
}
handleSubmit(e) {
const text = e.target.value.trim();
if (e.which === 13) {
this.props.onSave(text);
if (this.props.newTodo) {
this.setState({ text: '' });
}
}
}
handleChange(e) {
this.setState({ text: e.target.value });
}
handleBlur(e) {
if (!this.props.newTodo) {
this.props.onSave(e.target.value);
}
}
render() {
return (
<input
className={classnames({
edit: this.props.editing,
'new-todo': this.props.newTodo,
})}
type="text"
placeholder={this.props.placeholder}
autoFocus="true"
value={this.state.text}
onBlur={this.handleBlur.bind(this)}
onChange={this.handleChange.bind(this)}
onKeyDown={this.handleSubmit.bind(this)}
/>
);
}
}
TodoTextInput.propTypes = {
onSave: PropTypes.func.isRequired,
text: PropTypes.string,
placeholder: PropTypes.string,
editing: PropTypes.bool,
newTodo: PropTypes.bool,
};
export default TodoTextInput;

View File

@ -0,0 +1,6 @@
export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
export const EDIT_TODO = 'EDIT_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const COMPLETE_ALL = 'COMPLETE_ALL';
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED';

View File

@ -0,0 +1,3 @@
export const SHOW_ALL = 'show_all';
export const SHOW_COMPLETED = 'show_completed';
export const SHOW_ACTIVE = 'show_active';

View File

@ -0,0 +1,38 @@
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/todos';
class App extends Component {
render() {
const { todos, path, actions } = this.props;
return (
<div>
<Header addTodo={actions.addTodo} path={path} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
App.propTypes = {
todos: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
return {
todos: state.todos,
path: state.router.location.pathname,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(TodoActions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

View File

@ -0,0 +1,21 @@
import React, { Component, PropTypes } from 'react';
import { Provider } from 'react-redux';
import { Route, Redirect } from 'react-router';
import { ReduxRouter } from 'redux-router';
import Wrapper from './Wrapper';
import App from './App';
class Root extends Component {
render() {
return (
<ReduxRouter>
<Redirect from="/" to="Standard Todo" />
<Route path="/" component={Wrapper}>
<Route path="/:id" component={App} />
</Route>
</ReduxRouter>
);
}
}
export default Root;

View File

@ -0,0 +1,68 @@
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { pushState } from 'redux-router';
import { Route, Link } from 'react-router';
import * as TodoActions from '../actions/todos';
function mapDispatchToProps(dispatch) {
return {
pushState: bindActionCreators(pushState, dispatch),
actions: bindActionCreators(TodoActions, dispatch),
};
}
@connect((state) => ({}), mapDispatchToProps)
class Wrapper extends Component {
static propTypes = {
children: PropTypes.node,
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
event.preventDefault();
const { actions, pushState } = this.props;
const path = event.target.innerText;
pushState(null, path);
console.log('Navigate to', path);
if (this.timeout) clearInterval(this.timeout);
if (path === 'AutoTodo') {
console.log('!');
this.timeout = setInterval(() => {
actions.addTodo('Auto generated task');
}, 100);
}
}
render() {
return (
<div>
<div
style={{
padding: 20,
backgroundColor: '#eee',
fontWeight: 'bold',
textAlign: 'center',
}}
>
<a href="#" onClick={this.handleClick}>
Standard Todo
</a>{' '}
|{' '}
<a href="#" onClick={this.handleClick}>
AutoTodo
</a>
</div>
{this.props.children}
</div>
);
}
}
export default Wrapper;

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Redux TodoMVC example</title>
</head>
<body>
<div class="todoapp" id="root"></div>
<script src="/static/bundle.js"></script>
</body>
</html>

View File

@ -0,0 +1,16 @@
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import Root from './containers/Root';
import configureStore from './store/configureStore';
import 'todomvc-app-css/index.css';
const store = configureStore();
render(
<Provider store={store}>
<Root />
</Provider>,
document.getElementById('root')
);

View File

@ -0,0 +1,53 @@
{
"name": "redux-todomvc-example",
"version": "0.0.0",
"description": "Redux TodoMVC example",
"scripts": {
"start": "node server.js",
"test": "NODE_ENV=test mocha --recursive --compilers js:babel-core/register --require ./test/setup.js",
"test:watch": "npm test -- --watch"
},
"repository": {
"type": "git",
"url": "https://github.com/rackt/redux.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/rackt/redux/issues"
},
"homepage": "http://rackt.github.io/redux",
"dependencies": {
"classnames": "^2.1.2",
"history": "^1.13.1",
"react": "^0.14.0",
"react-dom": "^0.14.0",
"react-redux": "^4.0.0",
"react-router": "^1.0.2",
"redux": "^3.0.0",
"redux-router": "^1.0.0-beta5"
},
"devDependencies": {
"babel-core": "^6.3.15",
"babel-loader": "^6.2.0",
"babel-plugin-add-module-exports": "^0.1.1",
"babel-plugin-react-transform": "^2.0.0-beta1",
"babel-plugin-transform-decorators-legacy": "^1.2.0",
"babel-polyfill": "^6.3.14",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"expect": "^1.8.0",
"express": "^4.13.3",
"jsdom": "^5.6.1",
"mocha": "^2.2.5",
"node-libs-browser": "^0.5.2",
"raw-loader": "^0.5.1",
"react-addons-test-utils": "^0.14.0",
"react-transform-hmr": "^1.0.0",
"style-loader": "^0.12.3",
"todomvc-app-css": "^2.0.1",
"webpack": "^1.9.11",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.2.0"
}
}

View File

@ -0,0 +1,10 @@
import { combineReducers } from 'redux';
import { routerStateReducer } from 'redux-router';
import todos from './todos';
const rootReducer = combineReducers({
todos,
router: routerStateReducer,
});
export default rootReducer;

View File

@ -0,0 +1,61 @@
import {
ADD_TODO,
DELETE_TODO,
EDIT_TODO,
COMPLETE_TODO,
COMPLETE_ALL,
CLEAR_COMPLETED,
} from '../constants/ActionTypes';
const initialState = [
{
text: 'Use Redux',
completed: false,
id: 0,
},
];
export default function todos(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
return [
{
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
completed: false,
text: action.text,
},
...state,
];
case DELETE_TODO:
return state.filter((todo) => todo.id !== action.id);
case EDIT_TODO:
return state.map((todo) =>
todo.id === action.id
? Object.assign({}, todo, { text: action.text })
: todo
);
case COMPLETE_TODO:
return state.map((todo) =>
todo.id === action.id
? Object.assign({}, todo, { completed: !todo.completed })
: todo
);
case COMPLETE_ALL:
const areAllMarked = state.every((todo) => todo.completed);
return state.map((todo) =>
Object.assign({}, todo, {
completed: !areAllMarked,
})
);
case CLEAR_COMPLETED:
return state.filter((todo) => todo.completed === false);
default:
return state;
}
}

View File

@ -0,0 +1,32 @@
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var config = require('./webpack.config');
var app = new require('express')();
var port = 4002;
var compiler = webpack(config);
app.use(
webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
})
);
app.use(webpackHotMiddleware(compiler));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.listen(port, function (error) {
if (error) {
console.error(error);
} else {
console.info(
'==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.',
port,
port
);
}
});

View File

@ -0,0 +1,28 @@
import { createStore, compose } from 'redux';
import {
reduxReactRouter,
routerStateReducer,
ReduxRouter,
} from 'redux-router';
//import createHistory from 'history/lib/createBrowserHistory';
import createHistory from 'history/lib/createHashHistory';
import rootReducer from '../reducers';
export default function configureStore(initialState) {
let finalCreateStore = compose(
reduxReactRouter({ createHistory }),
global.devToolsExtension ? global.devToolsExtension() : (f) => f
)(createStore);
const store = finalCreateStore(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers');
store.replaceReducer(nextReducer);
});
}
return store;
}

View File

@ -0,0 +1,46 @@
import expect from 'expect';
import * as types from '../../constants/ActionTypes';
import * as actions from '../../actions/todos';
describe('todo actions', () => {
it('addTodo should create ADD_TODO action', () => {
expect(actions.addTodo('Use Redux')).toEqual({
type: types.ADD_TODO,
text: 'Use Redux',
});
});
it('deleteTodo should create DELETE_TODO action', () => {
expect(actions.deleteTodo(1)).toEqual({
type: types.DELETE_TODO,
id: 1,
});
});
it('editTodo should create EDIT_TODO action', () => {
expect(actions.editTodo(1, 'Use Redux everywhere')).toEqual({
type: types.EDIT_TODO,
id: 1,
text: 'Use Redux everywhere',
});
});
it('completeTodo should create COMPLETE_TODO action', () => {
expect(actions.completeTodo(1)).toEqual({
type: types.COMPLETE_TODO,
id: 1,
});
});
it('completeAll should create COMPLETE_ALL action', () => {
expect(actions.completeAll()).toEqual({
type: types.COMPLETE_ALL,
});
});
it('clearCompleted should create CLEAR_COMPLETED action', () => {
expect(actions.clearCompleted('Use Redux')).toEqual({
type: types.CLEAR_COMPLETED,
});
});
});

View File

@ -0,0 +1,108 @@
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import Footer from '../../components/Footer';
import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters';
function setup(propOverrides) {
const props = Object.assign(
{
completedCount: 0,
activeCount: 0,
filter: SHOW_ALL,
onClearCompleted: expect.createSpy(),
onShow: expect.createSpy(),
},
propOverrides
);
const renderer = TestUtils.createRenderer();
renderer.render(<Footer {...props} />);
const output = renderer.getRenderOutput();
return {
props: props,
output: output,
};
}
function getTextContent(elem) {
const children = Array.isArray(elem.props.children)
? elem.props.children
: [elem.props.children];
return children.reduce(function concatText(out, child) {
// Children are either elements or text strings
return out + (child.props ? getTextContent(child) : child);
}, '');
}
describe('components', () => {
describe('Footer', () => {
it('should render container', () => {
const { output } = setup();
expect(output.type).toBe('footer');
expect(output.props.className).toBe('footer');
});
it('should display active count when 0', () => {
const { output } = setup({ activeCount: 0 });
const [count] = output.props.children;
expect(getTextContent(count)).toBe('No items left');
});
it('should display active count when above 0', () => {
const { output } = setup({ activeCount: 1 });
const [count] = output.props.children;
expect(getTextContent(count)).toBe('1 item left');
});
it('should render filters', () => {
const { output } = setup();
const [, filters] = output.props.children;
expect(filters.type).toBe('ul');
expect(filters.props.className).toBe('filters');
expect(filters.props.children.length).toBe(3);
filters.props.children.forEach(function checkFilter(filter, i) {
expect(filter.type).toBe('li');
const a = filter.props.children;
expect(a.props.className).toBe(i === 0 ? 'selected' : '');
expect(a.props.children).toBe(
{
0: 'All',
1: 'Active',
2: 'Completed',
}[i]
);
});
});
it('should call onShow when a filter is clicked', () => {
const { output, props } = setup();
const [, filters] = output.props.children;
const filterLink = filters.props.children[1].props.children;
filterLink.props.onClick({});
expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE);
});
it('shouldnt show clear button when no completed todos', () => {
const { output } = setup({ completedCount: 0 });
const [, , clear] = output.props.children;
expect(clear).toBe(undefined);
});
it('should render clear button when completed todos', () => {
const { output } = setup({ completedCount: 1 });
const [, , clear] = output.props.children;
expect(clear.type).toBe('button');
expect(clear.props.children).toBe('Clear completed');
});
it('should call onClearCompleted on clear button click', () => {
const { output, props } = setup({ completedCount: 1 });
const [, , clear] = output.props.children;
clear.props.onClick({});
expect(props.onClearCompleted).toHaveBeenCalled();
});
});
});

View File

@ -0,0 +1,50 @@
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import Header from '../../components/Header';
import TodoTextInput from '../../components/TodoTextInput';
function setup() {
const props = {
addTodo: expect.createSpy(),
};
const renderer = TestUtils.createRenderer();
renderer.render(<Header {...props} />);
const output = renderer.getRenderOutput();
return {
props: props,
output: output,
renderer: renderer,
};
}
describe('components', () => {
describe('Header', () => {
it('should render correctly', () => {
const { output } = setup();
expect(output.type).toBe('header');
expect(output.props.className).toBe('header');
const [h1, input] = output.props.children;
expect(h1.type).toBe('h1');
expect(h1.props.children).toBe('todos');
expect(input.type).toBe(TodoTextInput);
expect(input.props.newTodo).toBe(true);
expect(input.props.placeholder).toBe('What needs to be done?');
});
it('should call call addTodo if length of text is greater than 0', () => {
const { output, props } = setup();
const input = output.props.children[1];
input.props.onSave('');
expect(props.addTodo.calls.length).toBe(0);
input.props.onSave('Use Redux');
expect(props.addTodo.calls.length).toBe(1);
});
});
});

View File

@ -0,0 +1,150 @@
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import MainSection from '../../components/MainSection';
import TodoItem from '../../components/TodoItem';
import Footer from '../../components/Footer';
import { SHOW_ALL, SHOW_COMPLETED } from '../../constants/TodoFilters';
function setup(propOverrides) {
const props = Object.assign(
{
todos: [
{
text: 'Use Redux',
completed: false,
id: 0,
},
{
text: 'Run the tests',
completed: true,
id: 1,
},
],
actions: {
editTodo: expect.createSpy(),
deleteTodo: expect.createSpy(),
completeTodo: expect.createSpy(),
completeAll: expect.createSpy(),
clearCompleted: expect.createSpy(),
},
},
propOverrides
);
const renderer = TestUtils.createRenderer();
renderer.render(<MainSection {...props} />);
const output = renderer.getRenderOutput();
return {
props: props,
output: output,
renderer: renderer,
};
}
describe('components', () => {
describe('MainSection', () => {
it('should render container', () => {
const { output } = setup();
expect(output.type).toBe('section');
expect(output.props.className).toBe('main');
});
describe('toggle all input', () => {
it('should render', () => {
const { output } = setup();
const [toggle] = output.props.children;
expect(toggle.type).toBe('input');
expect(toggle.props.type).toBe('checkbox');
expect(toggle.props.checked).toBe(false);
});
it('should be checked if all todos completed', () => {
const { output } = setup({
todos: [
{
text: 'Use Redux',
completed: true,
id: 0,
},
],
});
const [toggle] = output.props.children;
expect(toggle.props.checked).toBe(true);
});
it('should call completeAll on change', () => {
const { output, props } = setup();
const [toggle] = output.props.children;
toggle.props.onChange({});
expect(props.actions.completeAll).toHaveBeenCalled();
});
});
describe('footer', () => {
it('should render', () => {
const { output } = setup();
const [, , footer] = output.props.children;
expect(footer.type).toBe(Footer);
expect(footer.props.completedCount).toBe(1);
expect(footer.props.activeCount).toBe(1);
expect(footer.props.filter).toBe(SHOW_ALL);
});
it('onShow should set the filter', () => {
const { output, renderer } = setup();
const [, , footer] = output.props.children;
footer.props.onShow(SHOW_COMPLETED);
const updated = renderer.getRenderOutput();
const [, , updatedFooter] = updated.props.children;
expect(updatedFooter.props.filter).toBe(SHOW_COMPLETED);
});
it('onClearCompleted should call clearCompleted', () => {
const { output, props } = setup();
const [, , footer] = output.props.children;
footer.props.onClearCompleted();
expect(props.actions.clearCompleted).toHaveBeenCalled();
});
it('onClearCompleted shouldnt call clearCompleted if no todos completed', () => {
const { output, props } = setup({
todos: [
{
text: 'Use Redux',
completed: false,
id: 0,
},
],
});
const [, , footer] = output.props.children;
footer.props.onClearCompleted();
expect(props.actions.clearCompleted.calls.length).toBe(0);
});
});
describe('todo list', () => {
it('should render', () => {
const { output, props } = setup();
const [, list] = output.props.children;
expect(list.type).toBe('ul');
expect(list.props.children.length).toBe(2);
list.props.children.forEach((item, i) => {
expect(item.type).toBe(TodoItem);
expect(item.props.todo).toBe(props.todos[i]);
});
});
it('should filter items', () => {
const { output, renderer, props } = setup();
const [, , footer] = output.props.children;
footer.props.onShow(SHOW_COMPLETED);
const updated = renderer.getRenderOutput();
const [, updatedList] = updated.props.children;
expect(updatedList.props.children.length).toBe(1);
expect(updatedList.props.children[0].props.todo).toBe(props.todos[1]);
});
});
});
});

View File

@ -0,0 +1,118 @@
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import TodoItem from '../../components/TodoItem';
import TodoTextInput from '../../components/TodoTextInput';
function setup(editing = false) {
const props = {
todo: {
id: 0,
text: 'Use Redux',
completed: false,
},
editTodo: expect.createSpy(),
deleteTodo: expect.createSpy(),
completeTodo: expect.createSpy(),
};
const renderer = TestUtils.createRenderer();
renderer.render(<TodoItem {...props} />);
let output = renderer.getRenderOutput();
if (editing) {
const label = output.props.children.props.children[1];
label.props.onDoubleClick({});
output = renderer.getRenderOutput();
}
return {
props: props,
output: output,
renderer: renderer,
};
}
describe('components', () => {
describe('TodoItem', () => {
it('initial render', () => {
const { output } = setup();
expect(output.type).toBe('li');
expect(output.props.className).toBe('');
const div = output.props.children;
expect(div.type).toBe('div');
expect(div.props.className).toBe('view');
const [input, label, button] = div.props.children;
expect(input.type).toBe('input');
expect(input.props.checked).toBe(false);
expect(label.type).toBe('label');
expect(label.props.children).toBe('Use Redux');
expect(button.type).toBe('button');
expect(button.props.className).toBe('destroy');
});
it('input onChange should call completeTodo', () => {
const { output, props } = setup();
const input = output.props.children.props.children[0];
input.props.onChange({});
expect(props.completeTodo).toHaveBeenCalledWith(0);
});
it('button onClick should call deleteTodo', () => {
const { output, props } = setup();
const button = output.props.children.props.children[2];
button.props.onClick({});
expect(props.deleteTodo).toHaveBeenCalledWith(0);
});
it('label onDoubleClick should put component in edit state', () => {
const { output, renderer } = setup();
const label = output.props.children.props.children[1];
label.props.onDoubleClick({});
const updated = renderer.getRenderOutput();
expect(updated.type).toBe('li');
expect(updated.props.className).toBe('editing');
});
it('edit state render', () => {
const { output } = setup(true);
expect(output.type).toBe('li');
expect(output.props.className).toBe('editing');
const input = output.props.children;
expect(input.type).toBe(TodoTextInput);
expect(input.props.text).toBe('Use Redux');
expect(input.props.editing).toBe(true);
});
it('TodoTextInput onSave should call editTodo', () => {
const { output, props } = setup(true);
output.props.children.props.onSave('Use Redux');
expect(props.editTodo).toHaveBeenCalledWith(0, 'Use Redux');
});
it('TodoTextInput onSave should call deleteTodo if text is empty', () => {
const { output, props } = setup(true);
output.props.children.props.onSave('');
expect(props.deleteTodo).toHaveBeenCalledWith(0);
});
it('TodoTextInput onSave should exit component from edit state', () => {
const { output, renderer } = setup(true);
output.props.children.props.onSave('Use Redux');
const updated = renderer.getRenderOutput();
expect(updated.type).toBe('li');
expect(updated.props.className).toBe('');
});
});
});

View File

@ -0,0 +1,84 @@
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import TodoTextInput from '../../components/TodoTextInput';
function setup(propOverrides) {
const props = Object.assign(
{
onSave: expect.createSpy(),
text: 'Use Redux',
placeholder: 'What needs to be done?',
editing: false,
newTodo: false,
},
propOverrides
);
const renderer = TestUtils.createRenderer();
renderer.render(<TodoTextInput {...props} />);
let output = renderer.getRenderOutput();
output = renderer.getRenderOutput();
return {
props: props,
output: output,
renderer: renderer,
};
}
describe('components', () => {
describe('TodoTextInput', () => {
it('should render correctly', () => {
const { output } = setup();
expect(output.props.placeholder).toEqual('What needs to be done?');
expect(output.props.value).toEqual('Use Redux');
expect(output.props.className).toEqual('');
});
it('should render correctly when editing=true', () => {
const { output } = setup({ editing: true });
expect(output.props.className).toEqual('edit');
});
it('should render correctly when newTodo=true', () => {
const { output } = setup({ newTodo: true });
expect(output.props.className).toEqual('new-todo');
});
it('should update value on change', () => {
const { output, renderer } = setup();
output.props.onChange({ target: { value: 'Use Radox' } });
const updated = renderer.getRenderOutput();
expect(updated.props.value).toEqual('Use Radox');
});
it('should call onSave on return key press', () => {
const { output, props } = setup();
output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } });
expect(props.onSave).toHaveBeenCalledWith('Use Redux');
});
it('should reset state on return key press if newTodo', () => {
const { output, renderer } = setup({ newTodo: true });
output.props.onKeyDown({ which: 13, target: { value: 'Use Redux' } });
const updated = renderer.getRenderOutput();
expect(updated.props.value).toEqual('');
});
it('should call onSave on blur', () => {
const { output, props } = setup();
output.props.onBlur({ target: { value: 'Use Redux' } });
expect(props.onSave).toHaveBeenCalledWith('Use Redux');
});
it('shouldnt call onSave on blur if newTodo', () => {
const { output, props } = setup({ newTodo: true });
output.props.onBlur({ target: { value: 'Use Redux' } });
expect(props.onSave.calls.length).toBe(0);
});
});
});

View File

@ -0,0 +1,325 @@
import expect from 'expect';
import todos from '../../reducers/todos';
import * as types from '../../constants/ActionTypes';
describe('todos reducer', () => {
it('should handle initial state', () => {
expect(todos(undefined, {})).toEqual([
{
text: 'Use Redux',
completed: false,
id: 0,
},
]);
});
it('should handle ADD_TODO', () => {
expect(
todos([], {
type: types.ADD_TODO,
text: 'Run the tests',
})
).toEqual([
{
text: 'Run the tests',
completed: false,
id: 0,
},
]);
expect(
todos(
[
{
text: 'Use Redux',
completed: false,
id: 0,
},
],
{
type: types.ADD_TODO,
text: 'Run the tests',
}
)
).toEqual([
{
text: 'Run the tests',
completed: false,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
]);
expect(
todos(
[
{
text: 'Run the tests',
completed: false,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
],
{
type: types.ADD_TODO,
text: 'Fix the tests',
}
)
).toEqual([
{
text: 'Fix the tests',
completed: false,
id: 2,
},
{
text: 'Run the tests',
completed: false,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
]);
});
it('should handle DELETE_TODO', () => {
expect(
todos(
[
{
text: 'Run the tests',
completed: false,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
],
{
type: types.DELETE_TODO,
id: 1,
}
)
).toEqual([
{
text: 'Use Redux',
completed: false,
id: 0,
},
]);
});
it('should handle EDIT_TODO', () => {
expect(
todos(
[
{
text: 'Run the tests',
completed: false,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
],
{
type: types.EDIT_TODO,
text: 'Fix the tests',
id: 1,
}
)
).toEqual([
{
text: 'Fix the tests',
completed: false,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
]);
});
it('should handle COMPLETE_TODO', () => {
expect(
todos(
[
{
text: 'Run the tests',
completed: false,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
],
{
type: types.COMPLETE_TODO,
id: 1,
}
)
).toEqual([
{
text: 'Run the tests',
completed: true,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
]);
});
it('should handle COMPLETE_ALL', () => {
expect(
todos(
[
{
text: 'Run the tests',
completed: true,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
],
{
type: types.COMPLETE_ALL,
}
)
).toEqual([
{
text: 'Run the tests',
completed: true,
id: 1,
},
{
text: 'Use Redux',
completed: true,
id: 0,
},
]);
// Unmark if all todos are currently completed
expect(
todos(
[
{
text: 'Run the tests',
completed: true,
id: 1,
},
{
text: 'Use Redux',
completed: true,
id: 0,
},
],
{
type: types.COMPLETE_ALL,
}
)
).toEqual([
{
text: 'Run the tests',
completed: false,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
]);
});
it('should handle CLEAR_COMPLETED', () => {
expect(
todos(
[
{
text: 'Run the tests',
completed: true,
id: 1,
},
{
text: 'Use Redux',
completed: false,
id: 0,
},
],
{
type: types.CLEAR_COMPLETED,
}
)
).toEqual([
{
text: 'Use Redux',
completed: false,
id: 0,
},
]);
});
it('should not generate duplicate ids after CLEAR_COMPLETED', () => {
expect(
[
{
type: types.COMPLETE_TODO,
id: 0,
},
{
type: types.CLEAR_COMPLETED,
},
{
type: types.ADD_TODO,
text: 'Write more tests',
},
].reduce(todos, [
{
id: 0,
completed: false,
text: 'Use Redux',
},
{
id: 1,
completed: false,
text: 'Write tests',
},
])
).toEqual([
{
text: 'Write more tests',
completed: false,
id: 2,
},
{
text: 'Write tests',
completed: false,
id: 1,
},
]);
});
});

View File

@ -0,0 +1,5 @@
import { jsdom } from 'jsdom';
global.document = jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = global.window.navigator;

View File

@ -0,0 +1,32 @@
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: ['webpack-hot-middleware/client', './index'],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
],
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname,
},
{
test: /\.css?$/,
loaders: ['style', 'raw'],
include: __dirname,
},
],
},
};

View File

@ -0,0 +1,3 @@
{
"presets": ["es2015", "stage-0", "react"]
}

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Redux Saga Counter example</title>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="/static/bundle.js"></script>
</body>
</html>

View File

@ -0,0 +1,37 @@
{
"name": "redux-counter-example",
"version": "0.0.0",
"description": "Redux counter example",
"scripts": {
"start": "webpack-dev-server --progress"
},
"repository": {
"type": "git",
"url": "https://github.com/rackt/redux.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/rackt/redux/issues"
},
"homepage": "http://rackt.github.io/redux",
"dependencies": {
"prop-types": "^15.6.2",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^6.0.0",
"redux": "^4.0.0",
"redux-saga": "^0.10.5"
},
"devDependencies": {
"babel-cli": "^6.3.17",
"babel-core": "^6.3.17",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.0.0",
"babel-preset-react": "6.3.13",
"babel-preset-stage-0": "^6.3.13",
"webpack": "^4.0.0",
"webpack-cli": "^3.2.0",
"webpack-dev-server": "^3.1.0",
"webpack-hot-middleware": "^2.24.0"
}
}

View File

@ -0,0 +1,27 @@
import React from 'react';
import PropTypes from 'prop-types';
const Counter = ({
value,
onIncrement,
onIncrementAsync,
onDecrement,
onIncrementIfOdd,
}) => (
<p>
Clicked: {value} times <button onClick={onIncrement}>+</button>{' '}
<button onClick={onDecrement}>-</button>{' '}
<button onClick={onIncrementIfOdd}>Increment if odd</button>{' '}
<button onClick={onIncrementAsync}>Increment async</button>
</p>
);
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired,
onIncrementAsync: PropTypes.func.isRequired,
onIncrementIfOdd: PropTypes.func.isRequired,
};
export default Counter;

View File

@ -0,0 +1,43 @@
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
// import sagaMonitor from './sagaMonitor'
import Counter from './components/Counter';
import reducer from './reducers';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware(/* {sagaMonitor} */);
const composeEnhancers =
(window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
trace: true,
traceLimit: 25,
})) ||
compose;
const store = createStore(
reducer,
composeEnhancers(applyMiddleware(sagaMiddleware))
);
sagaMiddleware.run(rootSaga);
const action = (type) => store.dispatch({ type });
function render() {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => action('INCREMENT')}
onDecrement={() => action('DECREMENT')}
onIncrementIfOdd={() => action('INCREMENT_IF_ODD')}
onIncrementAsync={() => action('INCREMENT_ASYNC')}
/>,
document.getElementById('root')
);
}
render();
store.subscribe(render);

View File

@ -0,0 +1,12 @@
export default function counter(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'INCREMENT_IF_ODD':
return state % 2 !== 0 ? state + 1 : state;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}

View File

@ -0,0 +1,14 @@
/* eslint-disable no-constant-condition */
import { takeEvery } from 'redux-saga';
import { put, call } from 'redux-saga/effects';
import { delay } from 'redux-saga';
export function* incrementAsync() {
yield call(delay, 1000);
yield put({ type: 'INCREMENT' });
}
export default function* rootSaga() {
yield* takeEvery('INCREMENT_ASYNC', incrementAsync);
}

View File

@ -0,0 +1,25 @@
var path = require('path');
var webpack = require('webpack');
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: [path.join(__dirname, 'src', 'main')],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
module: {
rules: [
{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: /node_modules/,
},
],
},
devServer: {
port: 4003,
},
};

View File

@ -0,0 +1,3 @@
{
"presets": ["es2015", "stage-0", "react"]
}

View File

@ -0,0 +1 @@
export * from './todos';

View File

@ -0,0 +1,25 @@
import * as types from '../constants/ActionTypes';
export function addTodo(text) {
return { type: types.ADD_TODO, text };
}
export function deleteTodo(id) {
return { type: types.DELETE_TODO, id };
}
export function editTodo(id, text) {
return { type: types.EDIT_TODO, id, text };
}
export function completeTodo(id) {
return { type: types.COMPLETE_TODO, id };
}
export function completeAll() {
return { type: types.COMPLETE_ALL };
}
export function clearCompleted() {
return { type: types.CLEAR_COMPLETED };
}

View File

@ -0,0 +1,77 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import {
SHOW_ALL,
SHOW_COMPLETED,
SHOW_ACTIVE,
} from '../constants/TodoFilters';
const FILTER_TITLES = {
[SHOW_ALL]: 'All',
[SHOW_ACTIVE]: 'Active',
[SHOW_COMPLETED]: 'Completed',
};
class Footer extends Component {
renderTodoCount() {
const { activeCount } = this.props;
const itemWord = activeCount === 1 ? 'item' : 'items';
return (
<span className="todo-count">
<strong>{activeCount || 'No'}</strong> {itemWord} left
</span>
);
}
renderFilterLink(filter) {
const title = FILTER_TITLES[filter];
const { filter: selectedFilter, onShow } = this.props;
return (
<a
className={classnames({ selected: filter === selectedFilter })}
style={{ cursor: 'pointer' }}
onClick={() => onShow(filter)}
>
{title}
</a>
);
}
renderClearButton() {
const { completedCount, onClearCompleted } = this.props;
if (completedCount > 0) {
return (
<button className="clear-completed" onClick={onClearCompleted}>
Clear completed
</button>
);
}
}
render() {
return (
<footer className="footer">
{this.renderTodoCount()}
<ul className="filters">
{[SHOW_ALL, SHOW_ACTIVE, SHOW_COMPLETED].map((filter) => (
<li key={filter}>{this.renderFilterLink(filter)}</li>
))}
</ul>
{this.renderClearButton()}
</footer>
);
}
}
Footer.propTypes = {
completedCount: PropTypes.number.isRequired,
activeCount: PropTypes.number.isRequired,
filter: PropTypes.string.isRequired,
onClearCompleted: PropTypes.func.isRequired,
onShow: PropTypes.func.isRequired,
};
export default Footer;

View File

@ -0,0 +1,30 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TodoTextInput from './TodoTextInput';
class Header extends Component {
handleSave(text) {
if (text.length !== 0) {
this.props.addTodo(text);
}
}
render() {
return (
<header className="header">
<h1>todos</h1>
<TodoTextInput
newTodo
onSave={this.handleSave.bind(this)}
placeholder="What needs to be done?"
/>
</header>
);
}
}
Header.propTypes = {
addTodo: PropTypes.func.isRequired,
};
export default Header;

View File

@ -0,0 +1,95 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TodoItem from './TodoItem';
import Footer from './Footer';
import {
SHOW_ALL,
SHOW_COMPLETED,
SHOW_ACTIVE,
} from '../constants/TodoFilters';
const TODO_FILTERS = {
[SHOW_ALL]: () => true,
[SHOW_ACTIVE]: (todo) => !todo.completed,
[SHOW_COMPLETED]: (todo) => todo.completed,
};
class MainSection extends Component {
constructor(props, context) {
super(props, context);
this.state = { filter: SHOW_ALL };
}
handleClearCompleted() {
const atLeastOneCompleted = this.props.todos.some((todo) => todo.completed);
if (atLeastOneCompleted) {
this.props.actions.clearCompleted();
}
}
handleShow(filter) {
this.setState({ filter });
}
renderToggleAll(completedCount) {
const { todos, actions } = this.props;
if (todos.length > 0) {
return (
<input
className="toggle-all"
type="checkbox"
checked={completedCount === todos.length}
onChange={actions.completeAll}
/>
);
}
}
renderFooter(completedCount) {
const { todos } = this.props;
const { filter } = this.state;
const activeCount = todos.length - completedCount;
if (todos.length) {
return (
<Footer
completedCount={completedCount}
activeCount={activeCount}
filter={filter}
onClearCompleted={this.handleClearCompleted.bind(this)}
onShow={this.handleShow.bind(this)}
/>
);
}
}
render() {
const { todos, actions } = this.props;
const { filter } = this.state;
const filteredTodos = todos.filter(TODO_FILTERS[filter]);
const completedCount = todos.reduce(
(count, todo) => (todo.completed ? count + 1 : count),
0
);
return (
<section className="main">
{this.renderToggleAll(completedCount)}
<ul className="todo-list">
{filteredTodos.map((todo) => (
<TodoItem key={todo.id} todo={todo} {...actions} />
))}
</ul>
{this.renderFooter(completedCount)}
</section>
);
}
}
MainSection.propTypes = {
todos: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
export default MainSection;

View File

@ -0,0 +1,76 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import TodoTextInput from './TodoTextInput';
class TodoItem extends Component {
constructor(props, context) {
super(props, context);
this.state = {
editing: false,
};
}
handleDoubleClick() {
this.setState({ editing: true });
}
handleSave(id, text) {
if (text.length === 0) {
this.props.deleteTodo(id);
} else {
this.props.editTodo(id, text);
}
this.setState({ editing: false });
}
render() {
const { todo, completeTodo, deleteTodo } = this.props;
let element;
if (this.state.editing) {
element = (
<TodoTextInput
text={todo.text}
editing={this.state.editing}
onSave={(text) => this.handleSave(todo.id, text)}
/>
);
} else {
element = (
<div className="view">
<input
className="toggle"
type="checkbox"
checked={todo.completed}
onChange={() => completeTodo(todo.id)}
/>
<label onDoubleClick={this.handleDoubleClick.bind(this)}>
{todo.text}
</label>
<button className="destroy" onClick={() => deleteTodo(todo.id)} />
</div>
);
}
return (
<li
className={classnames({
completed: todo.completed,
editing: this.state.editing,
})}
>
{element}
</li>
);
}
}
TodoItem.propTypes = {
todo: PropTypes.object.isRequired,
editTodo: PropTypes.func.isRequired,
deleteTodo: PropTypes.func.isRequired,
completeTodo: PropTypes.func.isRequired,
};
export default TodoItem;

View File

@ -0,0 +1,60 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
class TodoTextInput extends Component {
constructor(props, context) {
super(props, context);
this.state = {
text: this.props.text || '',
};
}
handleSubmit(e) {
const text = e.target.value.trim();
if (e.which === 13) {
this.props.onSave(text);
if (this.props.newTodo) {
this.setState({ text: '' });
}
}
}
handleChange(e) {
this.setState({ text: e.target.value });
}
handleBlur(e) {
if (!this.props.newTodo) {
this.props.onSave(e.target.value);
}
}
render() {
return (
<input
className={classnames({
edit: this.props.editing,
'new-todo': this.props.newTodo,
})}
type="text"
placeholder={this.props.placeholder}
autoFocus={true}
value={this.state.text}
onBlur={this.handleBlur.bind(this)}
onChange={this.handleChange.bind(this)}
onKeyDown={this.handleSubmit.bind(this)}
/>
);
}
}
TodoTextInput.propTypes = {
onSave: PropTypes.func.isRequired,
text: PropTypes.string,
placeholder: PropTypes.string,
editing: PropTypes.bool,
newTodo: PropTypes.bool,
};
export default TodoTextInput;

View File

@ -0,0 +1,6 @@
export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
export const EDIT_TODO = 'EDIT_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const COMPLETE_ALL = 'COMPLETE_ALL';
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED';

View File

@ -0,0 +1,3 @@
export const SHOW_ALL = 'show_all';
export const SHOW_COMPLETED = 'show_completed';
export const SHOW_ACTIVE = 'show_active';

View File

@ -0,0 +1,38 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/todos';
class App extends Component {
render() {
const { todos, actions } = this.props;
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
App.propTypes = {
todos: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
return {
todos: state.todos,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(TodoActions, dispatch),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Redux TodoMVC example</title>
</head>
<body>
<div class="todoapp" id="root"></div>
<script src="/static/bundle.js"></script>
</body>
</html>

View File

@ -0,0 +1,16 @@
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
import 'todomvc-app-css/index.css';
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);

View File

@ -0,0 +1,42 @@
{
"name": "redux-todomvc-example",
"version": "0.0.0",
"description": "Redux TodoMVC example",
"scripts": {
"start": "node server.js",
"test": "NODE_ENV=test mocha --recursive --compilers js:babel-core/register --require ./test/setup.js",
"test:watch": "npm test -- --watch"
},
"repository": {
"type": "git",
"url": "https://github.com/rackt/redux.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/rackt/redux/issues"
},
"homepage": "http://rackt.github.io/redux",
"dependencies": {
"classnames": "^2.1.2",
"prop-types": "^15.6.2",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^6.0.0",
"redux": "^4.0.0"
},
"devDependencies": {
"babel-cli": "^6.3.17",
"babel-core": "^6.3.17",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.0.0",
"babel-preset-react": "6.3.13",
"babel-preset-stage-0": "^6.3.13",
"express": "^4.13.3",
"raw-loader": "^1.0.0",
"style-loader": "^0.23.0",
"todomvc-app-css": "^2.0.1",
"webpack": "^4.0.0",
"webpack-dev-server": "^3.0.0",
"webpack-hot-middleware": "^2.2.0"
}
}

Some files were not shown because too many files have changed in this diff Show More