From 6782f4ae414c681e7ee733d21a678f6cd2f12f1d Mon Sep 17 00:00:00 2001 From: Nathan Bierema Date: Mon, 26 Oct 2020 08:18:23 -0400 Subject: [PATCH] chore(extension): add extension (#658) * Move extension * prettier --- extension/.babelrc | 4 + extension/.bookignore | 8 + extension/.eslintignore | 8 + extension/.eslintrc | 30 + extension/.gitignore | 9 + extension/.travis.yml | 32 + extension/CHANGELOG.md | 4 + extension/CODE_OF_CONDUCT.md | 63 + extension/LICENSE | 21 + extension/README.md | 325 + extension/SUMMARY.md | 1 + extension/appveyor.yml | 18 + extension/book.json | 18 + extension/docs/API/Arguments.md | 324 + extension/docs/API/Methods.md | 93 + extension/docs/API/README.md | 4 + extension/docs/Articles.md | 5 + extension/docs/Credits.md | 11 + extension/docs/FAQ.md | 45 + extension/docs/Features/Trace.md | 13 + extension/docs/Feedback.md | 5 + extension/docs/Integrations.md | 302 + extension/docs/README.md | 21 + extension/docs/Recipes.md | 78 + extension/docs/Troubleshooting.md | 129 + extension/docs/Videos.md | 6 + extension/examples/buildAll.js | 36 + extension/examples/counter/.babelrc | 3 + extension/examples/counter/actions/counter.js | 37 + .../examples/counter/components/Counter.js | 32 + extension/examples/counter/containers/App.js | 16 + extension/examples/counter/index.html | 10 + extension/examples/counter/index.js | 14 + extension/examples/counter/package.json | 41 + .../examples/counter/reducers/counter.js | 12 + extension/examples/counter/reducers/index.js | 8 + extension/examples/counter/server.js | 32 + .../examples/counter/store/configureStore.js | 28 + .../counter/test/actions/counter.spec.js | 73 + .../counter/test/components/Counter.spec.js | 53 + .../counter/test/containers/App.spec.js | 53 + .../counter/test/reducers/counter.spec.js | 23 + extension/examples/counter/test/setup.js | 5 + extension/examples/counter/webpack.config.js | 23 + .../examples/react-counter-messaging/.babelrc | 3 + .../components/Counter.js | 62 + .../react-counter-messaging/index.html | 10 + .../examples/react-counter-messaging/index.js | 5 + .../react-counter-messaging/package.json | 33 + .../react-counter-messaging/webpack.config.js | 25 + extension/examples/router/.babelrc | 4 + extension/examples/router/actions/todos.js | 25 + .../examples/router/components/Footer.js | 76 + .../examples/router/components/Header.js | 30 + .../examples/router/components/MainSection.js | 94 + .../examples/router/components/TodoItem.js | 75 + .../router/components/TodoTextInput.js | 59 + .../examples/router/constants/ActionTypes.js | 6 + .../examples/router/constants/TodoFilters.js | 3 + extension/examples/router/containers/App.js | 38 + extension/examples/router/containers/Root.js | 21 + .../examples/router/containers/Wrapper.js | 68 + extension/examples/router/index.html | 10 + extension/examples/router/index.js | 16 + extension/examples/router/package.json | 53 + extension/examples/router/reducers/index.js | 10 + extension/examples/router/reducers/todos.js | 61 + extension/examples/router/server.js | 32 + .../examples/router/store/configureStore.js | 28 + .../router/test/actions/todos.spec.js | 46 + .../router/test/components/Footer.spec.js | 108 + .../router/test/components/Header.spec.js | 50 + .../test/components/MainSection.spec.js | 150 + .../router/test/components/TodoItem.spec.js | 118 + .../test/components/TodoTextInput.spec.js | 84 + .../router/test/reducers/todos.spec.js | 325 + extension/examples/router/test/setup.js | 5 + extension/examples/router/webpack.config.js | 32 + extension/examples/saga-counter/.babelrc | 3 + extension/examples/saga-counter/index.html | 13 + extension/examples/saga-counter/package.json | 37 + .../saga-counter/src/components/Counter.js | 27 + extension/examples/saga-counter/src/main.js | 43 + .../saga-counter/src/reducers/index.js | 12 + .../examples/saga-counter/src/sagas/index.js | 14 + .../examples/saga-counter/webpack.config.js | 25 + extension/examples/todomvc/.babelrc | 3 + extension/examples/todomvc/actions/index.js | 1 + extension/examples/todomvc/actions/todos.js | 25 + .../examples/todomvc/components/Footer.js | 77 + .../examples/todomvc/components/Header.js | 30 + .../todomvc/components/MainSection.js | 95 + .../examples/todomvc/components/TodoItem.js | 76 + .../todomvc/components/TodoTextInput.js | 60 + .../examples/todomvc/constants/ActionTypes.js | 6 + .../examples/todomvc/constants/TodoFilters.js | 3 + extension/examples/todomvc/containers/App.js | 38 + extension/examples/todomvc/index.html | 10 + extension/examples/todomvc/index.js | 16 + extension/examples/todomvc/package.json | 42 + extension/examples/todomvc/reducers/index.js | 8 + extension/examples/todomvc/reducers/todos.js | 67 + extension/examples/todomvc/server.js | 32 + .../examples/todomvc/store/configureStore.js | 30 + .../todomvc/test/actions/todos.spec.js | 46 + .../todomvc/test/components/Footer.spec.js | 108 + .../todomvc/test/components/Header.spec.js | 50 + .../test/components/MainSection.spec.js | 150 + .../todomvc/test/components/TodoItem.spec.js | 118 + .../test/components/TodoTextInput.spec.js | 84 + .../todomvc/test/reducers/todos.spec.js | 325 + extension/examples/todomvc/test/setup.js | 5 + extension/examples/todomvc/webpack.config.js | 28 + extension/gulpfile.babel.js | 195 + extension/package.json | 92 + extension/src/app/api/filters.js | 179 + extension/src/app/api/generateInstanceId.js | 5 + extension/src/app/api/importState.js | 72 + extension/src/app/api/index.js | 389 + extension/src/app/api/notifyErrors.js | 47 + extension/src/app/api/openWindow.js | 10 + extension/src/app/containers/App.js | 201 + extension/src/app/middlewares/api.js | 264 + .../src/app/middlewares/instanceSelector.js | 41 + extension/src/app/middlewares/panelSync.js | 31 + extension/src/app/middlewares/windowSync.js | 23 + .../src/app/reducers/background/index.js | 10 + .../app/reducers/background/persistStates.js | 4 + extension/src/app/reducers/panel/index.js | 16 + extension/src/app/reducers/window/index.js | 18 + .../src/app/reducers/window/instances.js | 23 + extension/src/app/service/Monitor.js | 52 + extension/src/app/stores/backgroundStore.js | 18 + extension/src/app/stores/createStore.js | 5 + extension/src/app/stores/enhancerStore.js | 30 + extension/src/app/stores/panelStore.js | 14 + extension/src/app/stores/windowStore.js | 47 + extension/src/assets/img/loading.svg | 42 + extension/src/assets/img/logo/128x128.png | Bin 0 -> 20670 bytes extension/src/assets/img/logo/16x16.png | Bin 0 -> 1883 bytes extension/src/assets/img/logo/38x38.png | Bin 0 -> 4877 bytes extension/src/assets/img/logo/48x48.png | Bin 0 -> 6320 bytes extension/src/assets/img/logo/error.png | Bin 0 -> 1751 bytes extension/src/assets/img/logo/gray.png | Bin 0 -> 3640 bytes extension/src/assets/img/logo/scalable.png | Bin 0 -> 12915 bytes .../extension/background/contextMenus.js | 37 + .../extension/background/getPreloadedState.js | 34 + .../src/browser/extension/background/index.js | 28 + .../browser/extension/background/logging.js | 37 + .../extension/background/openWindow.js | 66 + .../src/browser/extension/chromeAPIMock.js | 92 + .../src/browser/extension/devpanel/index.js | 102 + .../src/browser/extension/devtools/index.js | 17 + .../browser/extension/inject/contentScript.js | 130 + .../extension/inject/deprecatedWarn.js | 7 + .../src/browser/extension/inject/index.js | 20 + .../browser/extension/inject/pageScript.js | 478 + .../extension/inject/pageScriptWrap.js | 15 + extension/src/browser/extension/manifest.json | 73 + .../extension/options/AllowToRunGroup.js | 52 + .../extension/options/ContextMenuGroup.js | 25 + .../browser/extension/options/EditorGroup.js | 82 + .../browser/extension/options/FilterGroup.js | 70 + .../extension/options/MiscellaneousGroup.js | 53 + .../src/browser/extension/options/Options.js | 38 + .../src/browser/extension/options/index.js | 23 + .../browser/extension/options/syncOptions.js | 109 + .../src/browser/extension/window/index.js | 36 + .../src/browser/extension/window/remote.js | 35 + extension/src/browser/firefox/manifest.json | 65 + extension/src/browser/views/devpanel.pug | 15 + extension/src/browser/views/devtools.pug | 10 + .../src/browser/views/includes/style.pug | 64 + extension/src/browser/views/options.pug | 93 + extension/src/browser/views/remote.pug | 11 + extension/src/browser/views/window.pug | 17 + extension/test/.eslintrc | 11 + extension/test/app/containers/App.spec.js | 25 + extension/test/app/inject/api.spec.js | 98 + extension/test/app/inject/enhancer.spec.js | 217 + extension/test/app/setup.js | 31 + extension/test/chrome/extension.spec.js | 88 + extension/test/electron/devpanel.spec.js | 109 + extension/test/electron/fixture/index.html | 13 + extension/test/electron/fixture/main.js | 18 + extension/test/electron/fixture/package.json | 6 + extension/test/electron/fixture/renderer.js | 34 + extension/test/perf/data.js | 3660 +++++++ extension/test/perf/send.spec.js | 26 + extension/test/utils/e2e.js | 47 + extension/test/utils/inject.js | 17 + extension/webpack/base.config.js | 84 + extension/webpack/dev.config.js | 20 + extension/webpack/prod.config.js | 11 + .../replace/JsonpMainTemplate.runtime.js | 76 + extension/webpack/replace/log-apply-result.js | 36 + extension/webpack/wrap.config.js | 14 + extension/yarn.lock | 9676 +++++++++++++++++ 198 files changed, 23627 insertions(+) create mode 100644 extension/.babelrc create mode 100644 extension/.bookignore create mode 100644 extension/.eslintignore create mode 100644 extension/.eslintrc create mode 100644 extension/.gitignore create mode 100644 extension/.travis.yml create mode 100644 extension/CHANGELOG.md create mode 100644 extension/CODE_OF_CONDUCT.md create mode 100644 extension/LICENSE create mode 100644 extension/README.md create mode 100644 extension/SUMMARY.md create mode 100644 extension/appveyor.yml create mode 100644 extension/book.json create mode 100644 extension/docs/API/Arguments.md create mode 100644 extension/docs/API/Methods.md create mode 100644 extension/docs/API/README.md create mode 100644 extension/docs/Articles.md create mode 100644 extension/docs/Credits.md create mode 100644 extension/docs/FAQ.md create mode 100644 extension/docs/Features/Trace.md create mode 100644 extension/docs/Feedback.md create mode 100644 extension/docs/Integrations.md create mode 100644 extension/docs/README.md create mode 100644 extension/docs/Recipes.md create mode 100644 extension/docs/Troubleshooting.md create mode 100644 extension/docs/Videos.md create mode 100644 extension/examples/buildAll.js create mode 100644 extension/examples/counter/.babelrc create mode 100644 extension/examples/counter/actions/counter.js create mode 100644 extension/examples/counter/components/Counter.js create mode 100644 extension/examples/counter/containers/App.js create mode 100644 extension/examples/counter/index.html create mode 100644 extension/examples/counter/index.js create mode 100644 extension/examples/counter/package.json create mode 100644 extension/examples/counter/reducers/counter.js create mode 100644 extension/examples/counter/reducers/index.js create mode 100644 extension/examples/counter/server.js create mode 100644 extension/examples/counter/store/configureStore.js create mode 100644 extension/examples/counter/test/actions/counter.spec.js create mode 100644 extension/examples/counter/test/components/Counter.spec.js create mode 100644 extension/examples/counter/test/containers/App.spec.js create mode 100644 extension/examples/counter/test/reducers/counter.spec.js create mode 100644 extension/examples/counter/test/setup.js create mode 100644 extension/examples/counter/webpack.config.js create mode 100644 extension/examples/react-counter-messaging/.babelrc create mode 100644 extension/examples/react-counter-messaging/components/Counter.js create mode 100644 extension/examples/react-counter-messaging/index.html create mode 100644 extension/examples/react-counter-messaging/index.js create mode 100644 extension/examples/react-counter-messaging/package.json create mode 100644 extension/examples/react-counter-messaging/webpack.config.js create mode 100644 extension/examples/router/.babelrc create mode 100644 extension/examples/router/actions/todos.js create mode 100644 extension/examples/router/components/Footer.js create mode 100644 extension/examples/router/components/Header.js create mode 100644 extension/examples/router/components/MainSection.js create mode 100644 extension/examples/router/components/TodoItem.js create mode 100644 extension/examples/router/components/TodoTextInput.js create mode 100644 extension/examples/router/constants/ActionTypes.js create mode 100644 extension/examples/router/constants/TodoFilters.js create mode 100644 extension/examples/router/containers/App.js create mode 100644 extension/examples/router/containers/Root.js create mode 100644 extension/examples/router/containers/Wrapper.js create mode 100644 extension/examples/router/index.html create mode 100644 extension/examples/router/index.js create mode 100644 extension/examples/router/package.json create mode 100644 extension/examples/router/reducers/index.js create mode 100644 extension/examples/router/reducers/todos.js create mode 100644 extension/examples/router/server.js create mode 100644 extension/examples/router/store/configureStore.js create mode 100644 extension/examples/router/test/actions/todos.spec.js create mode 100644 extension/examples/router/test/components/Footer.spec.js create mode 100644 extension/examples/router/test/components/Header.spec.js create mode 100644 extension/examples/router/test/components/MainSection.spec.js create mode 100644 extension/examples/router/test/components/TodoItem.spec.js create mode 100644 extension/examples/router/test/components/TodoTextInput.spec.js create mode 100644 extension/examples/router/test/reducers/todos.spec.js create mode 100644 extension/examples/router/test/setup.js create mode 100644 extension/examples/router/webpack.config.js create mode 100644 extension/examples/saga-counter/.babelrc create mode 100644 extension/examples/saga-counter/index.html create mode 100644 extension/examples/saga-counter/package.json create mode 100644 extension/examples/saga-counter/src/components/Counter.js create mode 100644 extension/examples/saga-counter/src/main.js create mode 100644 extension/examples/saga-counter/src/reducers/index.js create mode 100644 extension/examples/saga-counter/src/sagas/index.js create mode 100644 extension/examples/saga-counter/webpack.config.js create mode 100644 extension/examples/todomvc/.babelrc create mode 100644 extension/examples/todomvc/actions/index.js create mode 100644 extension/examples/todomvc/actions/todos.js create mode 100644 extension/examples/todomvc/components/Footer.js create mode 100644 extension/examples/todomvc/components/Header.js create mode 100644 extension/examples/todomvc/components/MainSection.js create mode 100644 extension/examples/todomvc/components/TodoItem.js create mode 100644 extension/examples/todomvc/components/TodoTextInput.js create mode 100644 extension/examples/todomvc/constants/ActionTypes.js create mode 100644 extension/examples/todomvc/constants/TodoFilters.js create mode 100644 extension/examples/todomvc/containers/App.js create mode 100644 extension/examples/todomvc/index.html create mode 100644 extension/examples/todomvc/index.js create mode 100644 extension/examples/todomvc/package.json create mode 100644 extension/examples/todomvc/reducers/index.js create mode 100644 extension/examples/todomvc/reducers/todos.js create mode 100644 extension/examples/todomvc/server.js create mode 100644 extension/examples/todomvc/store/configureStore.js create mode 100644 extension/examples/todomvc/test/actions/todos.spec.js create mode 100644 extension/examples/todomvc/test/components/Footer.spec.js create mode 100644 extension/examples/todomvc/test/components/Header.spec.js create mode 100644 extension/examples/todomvc/test/components/MainSection.spec.js create mode 100644 extension/examples/todomvc/test/components/TodoItem.spec.js create mode 100644 extension/examples/todomvc/test/components/TodoTextInput.spec.js create mode 100644 extension/examples/todomvc/test/reducers/todos.spec.js create mode 100644 extension/examples/todomvc/test/setup.js create mode 100644 extension/examples/todomvc/webpack.config.js create mode 100644 extension/gulpfile.babel.js create mode 100644 extension/package.json create mode 100644 extension/src/app/api/filters.js create mode 100644 extension/src/app/api/generateInstanceId.js create mode 100644 extension/src/app/api/importState.js create mode 100644 extension/src/app/api/index.js create mode 100644 extension/src/app/api/notifyErrors.js create mode 100644 extension/src/app/api/openWindow.js create mode 100644 extension/src/app/containers/App.js create mode 100644 extension/src/app/middlewares/api.js create mode 100644 extension/src/app/middlewares/instanceSelector.js create mode 100644 extension/src/app/middlewares/panelSync.js create mode 100644 extension/src/app/middlewares/windowSync.js create mode 100644 extension/src/app/reducers/background/index.js create mode 100644 extension/src/app/reducers/background/persistStates.js create mode 100644 extension/src/app/reducers/panel/index.js create mode 100644 extension/src/app/reducers/window/index.js create mode 100644 extension/src/app/reducers/window/instances.js create mode 100644 extension/src/app/service/Monitor.js create mode 100644 extension/src/app/stores/backgroundStore.js create mode 100644 extension/src/app/stores/createStore.js create mode 100644 extension/src/app/stores/enhancerStore.js create mode 100644 extension/src/app/stores/panelStore.js create mode 100644 extension/src/app/stores/windowStore.js create mode 100644 extension/src/assets/img/loading.svg create mode 100644 extension/src/assets/img/logo/128x128.png create mode 100644 extension/src/assets/img/logo/16x16.png create mode 100644 extension/src/assets/img/logo/38x38.png create mode 100644 extension/src/assets/img/logo/48x48.png create mode 100644 extension/src/assets/img/logo/error.png create mode 100644 extension/src/assets/img/logo/gray.png create mode 100644 extension/src/assets/img/logo/scalable.png create mode 100644 extension/src/browser/extension/background/contextMenus.js create mode 100644 extension/src/browser/extension/background/getPreloadedState.js create mode 100644 extension/src/browser/extension/background/index.js create mode 100644 extension/src/browser/extension/background/logging.js create mode 100644 extension/src/browser/extension/background/openWindow.js create mode 100644 extension/src/browser/extension/chromeAPIMock.js create mode 100644 extension/src/browser/extension/devpanel/index.js create mode 100644 extension/src/browser/extension/devtools/index.js create mode 100644 extension/src/browser/extension/inject/contentScript.js create mode 100644 extension/src/browser/extension/inject/deprecatedWarn.js create mode 100644 extension/src/browser/extension/inject/index.js create mode 100644 extension/src/browser/extension/inject/pageScript.js create mode 100644 extension/src/browser/extension/inject/pageScriptWrap.js create mode 100644 extension/src/browser/extension/manifest.json create mode 100644 extension/src/browser/extension/options/AllowToRunGroup.js create mode 100644 extension/src/browser/extension/options/ContextMenuGroup.js create mode 100644 extension/src/browser/extension/options/EditorGroup.js create mode 100644 extension/src/browser/extension/options/FilterGroup.js create mode 100644 extension/src/browser/extension/options/MiscellaneousGroup.js create mode 100644 extension/src/browser/extension/options/Options.js create mode 100644 extension/src/browser/extension/options/index.js create mode 100644 extension/src/browser/extension/options/syncOptions.js create mode 100644 extension/src/browser/extension/window/index.js create mode 100644 extension/src/browser/extension/window/remote.js create mode 100644 extension/src/browser/firefox/manifest.json create mode 100644 extension/src/browser/views/devpanel.pug create mode 100644 extension/src/browser/views/devtools.pug create mode 100644 extension/src/browser/views/includes/style.pug create mode 100644 extension/src/browser/views/options.pug create mode 100644 extension/src/browser/views/remote.pug create mode 100644 extension/src/browser/views/window.pug create mode 100644 extension/test/.eslintrc create mode 100644 extension/test/app/containers/App.spec.js create mode 100644 extension/test/app/inject/api.spec.js create mode 100644 extension/test/app/inject/enhancer.spec.js create mode 100644 extension/test/app/setup.js create mode 100644 extension/test/chrome/extension.spec.js create mode 100644 extension/test/electron/devpanel.spec.js create mode 100644 extension/test/electron/fixture/index.html create mode 100644 extension/test/electron/fixture/main.js create mode 100644 extension/test/electron/fixture/package.json create mode 100644 extension/test/electron/fixture/renderer.js create mode 100644 extension/test/perf/data.js create mode 100644 extension/test/perf/send.spec.js create mode 100644 extension/test/utils/e2e.js create mode 100644 extension/test/utils/inject.js create mode 100644 extension/webpack/base.config.js create mode 100644 extension/webpack/dev.config.js create mode 100644 extension/webpack/prod.config.js create mode 100644 extension/webpack/replace/JsonpMainTemplate.runtime.js create mode 100644 extension/webpack/replace/log-apply-result.js create mode 100644 extension/webpack/wrap.config.js create mode 100644 extension/yarn.lock diff --git a/extension/.babelrc b/extension/.babelrc new file mode 100644 index 00000000..6cc845b9 --- /dev/null +++ b/extension/.babelrc @@ -0,0 +1,4 @@ +{ + "presets": ["es2015", "stage-0", "react"], + "plugins": ["add-module-exports", "transform-decorators-legacy"] +} diff --git a/extension/.bookignore b/extension/.bookignore new file mode 100644 index 00000000..91baa0de --- /dev/null +++ b/extension/.bookignore @@ -0,0 +1,8 @@ +src/ +build/ +dev/ +examples/ +npm-package/ +test/ +package.json +webpack/ \ No newline at end of file diff --git a/extension/.eslintignore b/extension/.eslintignore new file mode 100644 index 00000000..4a232330 --- /dev/null +++ b/extension/.eslintignore @@ -0,0 +1,8 @@ +node_modules +build +dev +webpack/replace +examples +test/app/setup.js +npm-package +_book diff --git a/extension/.eslintrc b/extension/.eslintrc new file mode 100644 index 00000000..7cbb31e0 --- /dev/null +++ b/extension/.eslintrc @@ -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"] +} diff --git a/extension/.gitignore b/extension/.gitignore new file mode 100644 index 00000000..bbe0a464 --- /dev/null +++ b/extension/.gitignore @@ -0,0 +1,9 @@ +node_modules +npm-debug.log +.DS_Store +.idea/ +dist/ +build/ +dev/ +tmp/ +_book diff --git a/extension/.travis.yml b/extension/.travis.yml new file mode 100644 index 00000000..d03640f9 --- /dev/null +++ b/extension/.travis.yml @@ -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 diff --git a/extension/CHANGELOG.md b/extension/CHANGELOG.md new file mode 100644 index 00000000..00b64307 --- /dev/null +++ b/extension/CHANGELOG.md @@ -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. diff --git a/extension/CODE_OF_CONDUCT.md b/extension/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..c44e8369 --- /dev/null +++ b/extension/CODE_OF_CONDUCT.md @@ -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 diff --git a/extension/LICENSE b/extension/LICENSE new file mode 100644 index 00000000..b34f2934 --- /dev/null +++ b/extension/LICENSE @@ -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. \ No newline at end of file diff --git a/extension/README.md b/extension/README.md new file mode 100644 index 00000000..74167cce --- /dev/null +++ b/extension/README.md @@ -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, we’re using Redux compose here. + +To specify [extension’s 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 extension’s 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 [extension’s 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 + ) +); +``` + +> There’re 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 don’t 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)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## 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)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +MIT + +## Created By + +If you like this, follow [@mdiordiev](https://twitter.com/mdiordiev) on twitter. diff --git a/extension/SUMMARY.md b/extension/SUMMARY.md new file mode 100644 index 00000000..542612fd --- /dev/null +++ b/extension/SUMMARY.md @@ -0,0 +1 @@ +./docs/README.md diff --git a/extension/appveyor.yml b/extension/appveyor.yml new file mode 100644 index 00000000..884e5b13 --- /dev/null +++ b/extension/appveyor.yml @@ -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 diff --git a/extension/book.json b/extension/book.json new file mode 100644 index 00000000..d7f27743 --- /dev/null +++ b/extension/book.json @@ -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 + } + } +} diff --git a/extension/docs/API/Arguments.md b/extension/docs/API/Arguments.md new file mode 100644 index 00000000..fe632424 --- /dev/null +++ b/extension/docs/API/Arguments.md @@ -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: '<>' } + : action; +const store = createStore( + rootReducer, + window.__REDUX_DEVTOOLS_EXTENSION__ && + window.__REDUX_DEVTOOLS_EXTENSION__({ + actionSanitizer, + stateSanitizer: (state) => + state.data ? { ...state, data: '<>' } : 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 extension’s 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. diff --git a/extension/docs/API/Methods.md b/extension/docs/API/Methods.md new file mode 100644 index 00000000..3d637601 --- /dev/null +++ b/extension/docs/API/Methods.md @@ -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) + + + +### 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. + + + +### 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. + + + +### 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. + + + +### 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`. + + + +### 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. diff --git a/extension/docs/API/README.md b/extension/docs/API/README.md new file mode 100644 index 00000000..13781355 --- /dev/null +++ b/extension/docs/API/README.md @@ -0,0 +1,4 @@ +# API Reference + +- [Parameters](Arguments.md) +- [Methods](Methods.md) diff --git a/extension/docs/Articles.md b/extension/docs/Articles.md new file mode 100644 index 00000000..09de66ad --- /dev/null +++ b/extension/docs/Articles.md @@ -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) diff --git a/extension/docs/Credits.md b/extension/docs/Credits.md new file mode 100644 index 00000000..f7ec16de --- /dev/null +++ b/extension/docs/Credits.md @@ -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). diff --git a/extension/docs/FAQ.md b/extension/docs/FAQ.md new file mode 100644 index 00000000..d46253b5 --- /dev/null +++ b/extension/docs/FAQ.md @@ -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=` 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). diff --git a/extension/docs/Features/Trace.md b/extension/docs/Features/Trace.md new file mode 100644 index 00000000..1aa2505b --- /dev/null +++ b/extension/docs/Features/Trace.md @@ -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). diff --git a/extension/docs/Feedback.md b/extension/docs/Feedback.md new file mode 100644 index 00000000..d31b7e6d --- /dev/null +++ b/extension/docs/Feedback.md @@ -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). + + diff --git a/extension/docs/Integrations.md b/extension/docs/Integrations.md new file mode 100644 index 00000000..ae27c64f --- /dev/null +++ b/extension/docs/Integrations.md @@ -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()); +} +``` diff --git a/extension/docs/README.md b/extension/docs/README.md new file mode 100644 index 00000000..f6df934a --- /dev/null +++ b/extension/docs/README.md @@ -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) diff --git a/extension/docs/Recipes.md b/extension/docs/Recipes.md new file mode 100644 index 00000000..5bc8e751 --- /dev/null +++ b/extension/docs/Recipes.md @@ -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; +}; + +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: '...', + }) + ) +); +``` diff --git a/extension/docs/Troubleshooting.md b/extension/docs/Troubleshooting.md new file mode 100644 index 00000000..e3cf226f --- /dev/null +++ b/extension/docs/Troubleshooting.md @@ -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: + +extensions + +### 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: '<>' } + : action; +const store = createStore( + rootReducer, + window.__REDUX_DEVTOOLS_EXTENSION__ && + window.__REDUX_DEVTOOLS_EXTENSION__({ + actionSanitizer, + stateSanitizer: (state) => + state.data ? { ...state, data: '<>' } : 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. diff --git a/extension/docs/Videos.md b/extension/docs/Videos.md new file mode 100644 index 00000000..bb4fbb82 --- /dev/null +++ b/extension/docs/Videos.md @@ -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) diff --git a/extension/examples/buildAll.js b/extension/examples/buildAll.js new file mode 100644 index 00000000..3a558760 --- /dev/null +++ b/extension/examples/buildAll.js @@ -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'); + } + } +} diff --git a/extension/examples/counter/.babelrc b/extension/examples/counter/.babelrc new file mode 100644 index 00000000..9b7d435a --- /dev/null +++ b/extension/examples/counter/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["es2015", "stage-0", "react"] +} diff --git a/extension/examples/counter/actions/counter.js b/extension/examples/counter/actions/counter.js new file mode 100644 index 00000000..94fcdca1 --- /dev/null +++ b/extension/examples/counter/actions/counter.js @@ -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); + }; +} diff --git a/extension/examples/counter/components/Counter.js b/extension/examples/counter/components/Counter.js new file mode 100644 index 00000000..08a0fcdb --- /dev/null +++ b/extension/examples/counter/components/Counter.js @@ -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 ( +

+ Clicked: {counter} times {' '} + {' '} + {' '} + +

+ ); + } +} + +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; diff --git a/extension/examples/counter/containers/App.js b/extension/examples/counter/containers/App.js new file mode 100644 index 00000000..47287ecf --- /dev/null +++ b/extension/examples/counter/containers/App.js @@ -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); diff --git a/extension/examples/counter/index.html b/extension/examples/counter/index.html new file mode 100644 index 00000000..0f963144 --- /dev/null +++ b/extension/examples/counter/index.html @@ -0,0 +1,10 @@ + + + + Redux counter example + + +
+ + + diff --git a/extension/examples/counter/index.js b/extension/examples/counter/index.js new file mode 100644 index 00000000..0ab7fd0f --- /dev/null +++ b/extension/examples/counter/index.js @@ -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( + + + , + document.getElementById('root') +); diff --git a/extension/examples/counter/package.json b/extension/examples/counter/package.json new file mode 100644 index 00000000..73fb3ab2 --- /dev/null +++ b/extension/examples/counter/package.json @@ -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" + } +} diff --git a/extension/examples/counter/reducers/counter.js b/extension/examples/counter/reducers/counter.js new file mode 100644 index 00000000..c16e5d44 --- /dev/null +++ b/extension/examples/counter/reducers/counter.js @@ -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; + } +} diff --git a/extension/examples/counter/reducers/index.js b/extension/examples/counter/reducers/index.js new file mode 100644 index 00000000..eba07a15 --- /dev/null +++ b/extension/examples/counter/reducers/index.js @@ -0,0 +1,8 @@ +import { combineReducers } from 'redux'; +import counter from './counter'; + +const rootReducer = combineReducers({ + counter, +}); + +export default rootReducer; diff --git a/extension/examples/counter/server.js b/extension/examples/counter/server.js new file mode 100644 index 00000000..7e993c75 --- /dev/null +++ b/extension/examples/counter/server.js @@ -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 + ); + } +}); diff --git a/extension/examples/counter/store/configureStore.js b/extension/examples/counter/store/configureStore.js new file mode 100644 index 00000000..a36c0d53 --- /dev/null +++ b/extension/examples/counter/store/configureStore.js @@ -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; +} diff --git a/extension/examples/counter/test/actions/counter.spec.js b/extension/examples/counter/test/actions/counter.spec.js new file mode 100644 index 00000000..c65cc240 --- /dev/null +++ b/extension/examples/counter/test/actions/counter.spec.js @@ -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)); + }); +}); diff --git a/extension/examples/counter/test/components/Counter.spec.js b/extension/examples/counter/test/components/Counter.spec.js new file mode 100644 index 00000000..85f0e163 --- /dev/null +++ b/extension/examples/counter/test/components/Counter.spec.js @@ -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( + + ); + 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(); + }); +}); diff --git a/extension/examples/counter/test/containers/App.spec.js b/extension/examples/counter/test/containers/App.spec.js new file mode 100644 index 00000000..bfa4d73d --- /dev/null +++ b/extension/examples/counter/test/containers/App.spec.js @@ -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( + + + + ); + 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/); + }); + }); +}); diff --git a/extension/examples/counter/test/reducers/counter.spec.js b/extension/examples/counter/test/reducers/counter.spec.js new file mode 100644 index 00000000..45861187 --- /dev/null +++ b/extension/examples/counter/test/reducers/counter.spec.js @@ -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); + }); + }); +}); diff --git a/extension/examples/counter/test/setup.js b/extension/examples/counter/test/setup.js new file mode 100644 index 00000000..b4e5ab07 --- /dev/null +++ b/extension/examples/counter/test/setup.js @@ -0,0 +1,5 @@ +import { jsdom } from 'jsdom'; + +global.document = jsdom(''); +global.window = document.defaultView; +global.navigator = global.window.navigator; diff --git a/extension/examples/counter/webpack.config.js b/extension/examples/counter/webpack.config.js new file mode 100644 index 00000000..d7aff9b1 --- /dev/null +++ b/extension/examples/counter/webpack.config.js @@ -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/, + }, + ], + }, +}; diff --git a/extension/examples/react-counter-messaging/.babelrc b/extension/examples/react-counter-messaging/.babelrc new file mode 100644 index 00000000..9b7d435a --- /dev/null +++ b/extension/examples/react-counter-messaging/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["es2015", "stage-0", "react"] +} diff --git a/extension/examples/react-counter-messaging/components/Counter.js b/extension/examples/react-counter-messaging/components/Counter.js new file mode 100644 index 00000000..97eda01c --- /dev/null +++ b/extension/examples/react-counter-messaging/components/Counter.js @@ -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 ( +

+ Clicked: {counter} times {' '} + +

+ ); + } +} + +export default Counter; diff --git a/extension/examples/react-counter-messaging/index.html b/extension/examples/react-counter-messaging/index.html new file mode 100644 index 00000000..f877ce0b --- /dev/null +++ b/extension/examples/react-counter-messaging/index.html @@ -0,0 +1,10 @@ + + + + React counter example + + +
+ + + diff --git a/extension/examples/react-counter-messaging/index.js b/extension/examples/react-counter-messaging/index.js new file mode 100644 index 00000000..988779bb --- /dev/null +++ b/extension/examples/react-counter-messaging/index.js @@ -0,0 +1,5 @@ +import React from 'react'; +import { render } from 'react-dom'; +import Counter from './components/Counter'; + +render(, document.getElementById('root')); diff --git a/extension/examples/react-counter-messaging/package.json b/extension/examples/react-counter-messaging/package.json new file mode 100644 index 00000000..97db9897 --- /dev/null +++ b/extension/examples/react-counter-messaging/package.json @@ -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" + } +} diff --git a/extension/examples/react-counter-messaging/webpack.config.js b/extension/examples/react-counter-messaging/webpack.config.js new file mode 100644 index 00000000..43f3ab5b --- /dev/null +++ b/extension/examples/react-counter-messaging/webpack.config.js @@ -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, + }, +}; diff --git a/extension/examples/router/.babelrc b/extension/examples/router/.babelrc new file mode 100644 index 00000000..6cc845b9 --- /dev/null +++ b/extension/examples/router/.babelrc @@ -0,0 +1,4 @@ +{ + "presets": ["es2015", "stage-0", "react"], + "plugins": ["add-module-exports", "transform-decorators-legacy"] +} diff --git a/extension/examples/router/actions/todos.js b/extension/examples/router/actions/todos.js new file mode 100644 index 00000000..64247221 --- /dev/null +++ b/extension/examples/router/actions/todos.js @@ -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 }; +} diff --git a/extension/examples/router/components/Footer.js b/extension/examples/router/components/Footer.js new file mode 100644 index 00000000..8972bd8a --- /dev/null +++ b/extension/examples/router/components/Footer.js @@ -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 ( + + {activeCount || 'No'} {itemWord} left + + ); + } + + renderFilterLink(filter) { + const title = FILTER_TITLES[filter]; + const { filter: selectedFilter, onShow } = this.props; + + return ( + onShow(filter)} + > + {title} + + ); + } + + renderClearButton() { + const { completedCount, onClearCompleted } = this.props; + if (completedCount > 0) { + return ( + + ); + } + } + + render() { + return ( +
+ {this.renderTodoCount()} +
    + {[SHOW_ALL, SHOW_ACTIVE, SHOW_COMPLETED].map((filter) => ( +
  • {this.renderFilterLink(filter)}
  • + ))} +
+ {this.renderClearButton()} +
+ ); + } +} + +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; diff --git a/extension/examples/router/components/Header.js b/extension/examples/router/components/Header.js new file mode 100644 index 00000000..e09a2e27 --- /dev/null +++ b/extension/examples/router/components/Header.js @@ -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 ( +
+

{path}

+ +
+ ); + } +} + +Header.propTypes = { + addTodo: PropTypes.func.isRequired, +}; + +export default Header; diff --git a/extension/examples/router/components/MainSection.js b/extension/examples/router/components/MainSection.js new file mode 100644 index 00000000..51b86378 --- /dev/null +++ b/extension/examples/router/components/MainSection.js @@ -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 ( + + ); + } + } + + renderFooter(completedCount) { + const { todos } = this.props; + const { filter } = this.state; + const activeCount = todos.length - completedCount; + + if (todos.length) { + return ( +