feat(redux-devtools): convert counter example to TypeScript (#616)

* stash

* finish

* optional
This commit is contained in:
Nathan Bierema 2020-08-27 18:44:02 -04:00 committed by GitHub
parent 2faa16319b
commit f1e3f4f834
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 321 additions and 122 deletions

View File

@ -13,7 +13,11 @@
},
"scripts": {
"start": "webpack-dev-server --open",
"stats": "NODE_ENV=production webpack --json > dist/stats.json"
"stats": "NODE_ENV=production webpack --json > dist/stats.json",
"lint": "eslint . --ext .ts,.tsx",
"lint:fix": "eslint . --ext .ts,.tsx --fix",
"type-check": "tsc --noEmit",
"type-check:watch": "npm run type-check -- --watch"
},
"dependencies": {
"immutable": "^4.0.0-rc.12",

View File

@ -23,6 +23,29 @@ interface KeyObject {
sequence: string;
}
interface ExternalProps<S, A extends Action<unknown>> {
defaultPosition: 'left' | 'top' | 'right' | 'bottom';
defaultIsVisible: boolean;
defaultSize: number;
toggleVisibilityKey: string;
changePositionKey: string;
changeMonitorKey?: string;
fluid: boolean;
dispatch: Dispatch<DockMonitorAction>;
children:
| Monitor<S, A, LiftedState<S, A, unknown>, unknown, Action<unknown>>
| Monitor<S, A, LiftedState<S, A, unknown>, unknown, Action<unknown>>[];
}
interface DefaultProps {
defaultIsVisible: boolean;
defaultPosition: 'left' | 'top' | 'right' | 'bottom';
defaultSize: number;
fluid: boolean;
}
export interface DockMonitorProps<S, A extends Action<unknown>>
extends LiftedState<S, A, DockMonitorState> {
defaultPosition: 'left' | 'top' | 'right' | 'bottom';
@ -40,10 +63,9 @@ export interface DockMonitorProps<S, A extends Action<unknown>>
| Monitor<S, A, LiftedState<S, A, unknown>, unknown, Action<unknown>>[];
}
export default class DockMonitor<
S,
A extends Action<unknown>
> extends Component<DockMonitorProps<S, A>> {
class DockMonitor<S, A extends Action<unknown>> extends Component<
DockMonitorProps<S, A>
> {
static update = reducer;
static propTypes = {
@ -64,7 +86,7 @@ export default class DockMonitor<
}),
};
static defaultProps = {
static defaultProps: DefaultProps = {
defaultIsVisible: true,
defaultPosition: 'right',
defaultSize: 0.3,
@ -212,3 +234,14 @@ export default class DockMonitor<
);
}
}
export default (DockMonitor as unknown) as React.ComponentType<
ExternalProps<unknown, Action<unknown>>
> & {
update(
monitorProps: ExternalProps<unknown, Action<unknown>>,
state: DockMonitorState | undefined,
action: DockMonitorAction
): DockMonitorState;
defaultProps: DefaultProps;
};

View File

@ -13,6 +13,8 @@ import reducer, { LogMonitorState } from './reducers';
import LogMonitorButtonBar from './LogMonitorButtonBar';
import LogMonitorEntryList from './LogMonitorEntryList';
import debounce from 'lodash.debounce';
import { DockMonitorState } from 'redux-devtools-dock-monitor/lib/reducers';
import { DockMonitorAction } from 'redux-devtools-dock-monitor/lib/actions';
// eslint-disable-next-line @typescript-eslint/unbound-method
const { toggleAction, setActionsActive } = ActionCreators;
@ -41,6 +43,27 @@ const styles: {
},
};
interface ExternalProps<S, A extends Action<unknown>> {
dispatch: Dispatch<LogMonitorAction | LiftedAction<S, A, LogMonitorState>>;
preserveScrollTop: boolean;
select: (state: S) => unknown;
theme: keyof typeof themes | Base16Theme;
expandActionRoot: boolean;
expandStateRoot: boolean;
markStateDiff: boolean;
hideMainButtons?: boolean;
}
interface DefaultProps<S> {
select: (state: unknown) => unknown;
theme: keyof typeof themes | Base16Theme;
preserveScrollTop: boolean;
expandActionRoot: boolean;
expandStateRoot: boolean;
markStateDiff: boolean;
}
export interface LogMonitorProps<S, A extends Action<unknown>>
extends LiftedState<S, A, LogMonitorState> {
dispatch: Dispatch<LogMonitorAction | LiftedAction<S, A, LogMonitorState>>;
@ -54,10 +77,9 @@ export interface LogMonitorProps<S, A extends Action<unknown>>
hideMainButtons?: boolean;
}
export default class LogMonitor<
S,
A extends Action<unknown>
> extends PureComponent<LogMonitorProps<S, A>> {
class LogMonitor<S, A extends Action<unknown>> extends PureComponent<
LogMonitorProps<S, A>
> {
static update = reducer;
static propTypes = {
@ -80,7 +102,7 @@ export default class LogMonitor<
hideMainButtons: PropTypes.bool,
};
static defaultProps = {
static defaultProps: DefaultProps<unknown> = {
select: (state: unknown) => state,
theme: 'nicinabox',
preserveScrollTop: true,
@ -248,3 +270,14 @@ export default class LogMonitor<
);
}
}
export default (LogMonitor as unknown) as React.ComponentType<
ExternalProps<unknown, Action<unknown>>
> & {
update(
monitorProps: ExternalProps<unknown, Action<unknown>>,
state: DockMonitorState | undefined,
action: DockMonitorAction
): DockMonitorState;
defaultProps: DefaultProps<unknown>;
};

View File

@ -1,5 +1,9 @@
{
"presets": ["@babel/preset-env", "@babel/preset-react"],
"presets": [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"react-hot-loader/babel"

View File

@ -0,0 +1,21 @@
module.exports = {
extends: '../../../../.eslintrc',
overrides: [
{
files: ['*.ts', '*.tsx'],
extends: '../../../../eslintrc.ts.react.base.json',
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
},
},
{
files: ['webpack.config.ts'],
extends: '../../../../eslintrc.ts.base.json',
parserOptions: {
tsconfigRootDir: __dirname,
project: ['./tsconfig.webpack.json'],
},
},
],
};

View File

@ -2,20 +2,22 @@
"name": "counter-redux",
"version": "0.0.1",
"description": "Counter example for redux",
"private": true,
"main": "src/index.js",
"scripts": {
"start": "webpack-dev-server --open"
"homepage": "https://github.com/reduxjs/redux-devtools/tree/master/packages/redux-devtools/examples/counter",
"bugs": {
"url": "https://github.com/reduxjs/redux-devtools/issues"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/reduxjs/redux-devtools.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/reduxjs/redux-devtools/issues"
"scripts": {
"start": "webpack-dev-server --open",
"lint": "eslint . --ext .ts,.tsx",
"lint:fix": "eslint . --ext .ts,.tsx --fix",
"type-check": "tsc --noEmit",
"type-check:watch": "npm run type-check -- --watch"
},
"homepage": "https://github.com/reduxjs/redux-devtools#readme",
"dependencies": {
"prop-types": "^15.7.2",
"react": "^16.13.1",
@ -23,18 +25,17 @@
"react-hot-loader": "^4.12.21",
"react-redux": "^7.2.1",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"@babel/core": "^7.11.1",
"@babel/plugin-proposal-class-properties": "^7.10.4",
"@babel/preset-env": "^7.11.0",
"@babel/preset-react": "^7.10.4",
"babel-loader": "^8.1.0",
"redux-devtools": "^3.6.1",
"redux-devtools-dock-monitor": "^1.1.4",
"redux-devtools-log-monitor": "^2.0.1",
"webpack": "^4.44.1",
"webpack-dev-server": "^3.11.0"
}
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"@types/prop-types": "^15.7.3",
"@types/react": "^16.9.46",
"@types/react-dom": "^16.9.8",
"@types/react-redux": "^7.1.9",
"@types/webpack-env": "^1.15.2"
},
"private": true
}

View File

@ -1,33 +0,0 @@
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../constants/ActionTypes';
export function increment() {
return {
type: INCREMENT_COUNTER,
};
}
export function decrement() {
return {
type: DECREMENT_COUNTER,
};
}
export function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState();
if (counter % 2 === 0) {
return;
}
dispatch(increment());
};
}
export function incrementAsync() {
return (dispatch) => {
setTimeout(() => {
dispatch(increment());
}, 1000);
};
}

View File

@ -0,0 +1,53 @@
import { ThunkAction } from 'redux-thunk';
import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../constants/ActionTypes';
import { CounterState } from '../reducers';
interface IncrementCounterAction {
type: typeof INCREMENT_COUNTER;
}
export function increment(): IncrementCounterAction {
return {
type: INCREMENT_COUNTER,
};
}
interface DecrementCounterAction {
type: typeof DECREMENT_COUNTER;
}
export function decrement(): DecrementCounterAction {
return {
type: DECREMENT_COUNTER,
};
}
export type CounterAction = IncrementCounterAction | DecrementCounterAction;
export function incrementIfOdd(): ThunkAction<
void,
CounterState,
never,
CounterAction
> {
return (dispatch, getState) => {
const { counter } = getState();
if (counter % 2 === 0) {
return;
}
dispatch(increment());
};
}
export function incrementAsync(): ThunkAction<
void,
CounterState,
never,
CounterAction
> {
return (dispatch) => {
setTimeout(() => {
dispatch(increment());
}, 1000);
};
}

View File

@ -1,7 +1,14 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class Counter extends Component {
interface Props {
increment: () => void;
incrementIfOdd: () => void;
decrement: () => void;
counter: number;
}
export default class Counter extends Component<Props> {
static propTypes = {
increment: PropTypes.func.isRequired,
incrementIfOdd: PropTypes.func.isRequired,

View File

@ -1,10 +1,17 @@
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { bindActionCreators, Dispatch } from 'redux';
import { connect } from 'react-redux';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/CounterActions';
import { CounterAction } from '../actions/CounterActions';
import { CounterState } from '../reducers';
class CounterApp extends Component {
interface Props {
counter: number;
dispatch: Dispatch<CounterAction>;
}
class CounterApp extends Component<Props> {
render() {
const { counter, dispatch } = this.props;
return (
@ -16,7 +23,7 @@ class CounterApp extends Component {
}
}
function select(state) {
function select(state: CounterState) {
return {
counter: state.counter,
};

View File

@ -1,10 +1,17 @@
import { hot } from 'react-hot-loader/root';
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { Store } from 'redux';
import CounterApp from './CounterApp';
import DevTools from './DevTools';
import { CounterState } from '../reducers';
import { CounterAction } from '../actions/CounterActions';
class Root extends Component {
interface Props {
store: Store<CounterState, CounterAction>;
}
class Root extends Component<Props> {
render() {
const { store } = this.props;
return (

View File

@ -1,5 +0,0 @@
if (process.env.NODE_ENV === 'production') {
module.exports = require('./Root.prod');
} else {
module.exports = require('./Root.dev');
}

View File

@ -1,9 +1,16 @@
import { hot } from 'react-hot-loader/root';
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { Store } from 'redux';
import CounterApp from './CounterApp';
import { CounterState } from '../reducers';
import { CounterAction } from '../actions/CounterActions';
class Root extends Component {
interface Props {
store: Store<CounterState, CounterAction>;
}
class Root extends Component<Props> {
render() {
const { store } = this.props;
return (

View File

@ -0,0 +1,15 @@
import { Store } from 'redux';
import { CounterState } from '../reducers';
import { CounterAction } from '../actions/CounterActions';
import { ComponentType } from 'react';
interface Props {
store: Store<CounterState, CounterAction>;
}
const Root: ComponentType<Props> =
process.env.NODE_ENV === 'production'
? // eslint-disable-next-line @typescript-eslint/no-var-requires
require('./Root.prod').default
: // eslint-disable-next-line @typescript-eslint/no-var-requires
require('./Root.dev').default;
export default Root;

View File

@ -15,6 +15,7 @@ render(
if (module.hot) {
module.hot.accept('./containers/Root', () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const RootContainer = require('./containers/Root').default;
render(
<AppContainer>

View File

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

View File

@ -5,4 +5,8 @@ const rootReducer = combineReducers({
counter,
});
export interface CounterState {
counter: number;
}
export default rootReducer;

View File

@ -1,23 +0,0 @@
import { createStore, applyMiddleware, compose } from 'redux';
import { persistState } from 'redux-devtools';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
import DevTools from '../containers/DevTools';
const enhancer = compose(
applyMiddleware(thunk),
DevTools.instrument(),
persistState(window.location.href.match(/[?&]debug_session=([^&#]+)\b/))
);
export default function configureStore(initialState) {
const store = createStore(rootReducer, initialState, enhancer);
if (module.hot) {
module.hot.accept('../reducers', () =>
store.replaceReducer(require('../reducers').default)
);
}
return store;
}

View File

@ -0,0 +1,31 @@
import { createStore, applyMiddleware, compose, PreloadedState } from 'redux';
import { persistState } from 'redux-devtools';
import thunk from 'redux-thunk';
import rootReducer, { CounterState } from '../reducers';
import DevTools from '../containers/DevTools';
function getDebugSessionKey() {
const matches = /[?&]debug_session=([^&#]+)\b/.exec(window.location.href);
return matches && matches.length > 0 ? matches[1] : null;
}
const enhancer = compose(
applyMiddleware(thunk),
DevTools.instrument(),
persistState(getDebugSessionKey())
);
export default function configureStore(
initialState?: PreloadedState<CounterState>
) {
const store = createStore(rootReducer, initialState, enhancer);
if (module.hot) {
module.hot.accept('../reducers', () =>
// eslint-disable-next-line @typescript-eslint/no-var-requires
store.replaceReducer(require('../reducers').default)
);
}
return store;
}

View File

@ -1,5 +0,0 @@
if (process.env.NODE_ENV === 'production') {
module.exports = require('./configureStore.prod');
} else {
module.exports = require('./configureStore.dev');
}

View File

@ -1,9 +0,0 @@
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const enhancer = applyMiddleware(thunk);
export default function configureStore(initialState) {
return createStore(rootReducer, initialState, enhancer);
}

View File

@ -0,0 +1,11 @@
import { createStore, applyMiddleware, PreloadedState } from 'redux';
import thunk from 'redux-thunk';
import rootReducer, { CounterState } from '../reducers';
const enhancer = applyMiddleware(thunk);
export default function configureStore(
initialState?: PreloadedState<CounterState>
) {
return createStore(rootReducer, initialState, enhancer);
}

View File

@ -0,0 +1,13 @@
import { PreloadedState, Store } from 'redux';
import { CounterState } from '../reducers';
import { CounterAction } from '../actions/CounterActions';
const configureStore: (
initialState?: PreloadedState<CounterState>
) => Store<CounterState, CounterAction> =
process.env.NODE_ENV === 'production'
? // eslint-disable-next-line @typescript-eslint/no-var-requires
require('./configureStore.prod').default
: // eslint-disable-next-line @typescript-eslint/no-var-requires
require('./configureStore.dev').default;
export default configureStore;

View File

@ -0,0 +1,7 @@
{
"extends": "../../../../tsconfig.react.base.json",
"compilerOptions": {
"outDir": "lib"
},
"include": ["src"]
}

View File

@ -0,0 +1,4 @@
{
"extends": "../../../../tsconfig.base.json",
"include": ["webpack.config.ts"]
}

View File

@ -1,9 +1,8 @@
var path = require('path');
var webpack = require('webpack');
import * as path from 'path';
import * as webpack from 'webpack';
module.exports = {
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
devtool: 'eval-source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
@ -14,20 +13,24 @@ module.exports = {
filename: 'bundle.js',
publicPath: '/static/',
},
plugins: [new webpack.HotModuleReplacementPlugin()],
module: {
rules: [
{
test: /\.js$/,
test: /\.(js|ts)x?$/,
loaders: ['babel-loader'],
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
},
],
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
historyApiFallback: true,
hot: true,
port: 3000,
},
devtool: 'eval-source-map',
};

View File

@ -25,7 +25,7 @@ function logError(type: string) {
}
}
interface Props<
export interface Props<
S,
A extends Action<unknown>,
MonitorState,
@ -78,7 +78,9 @@ export default function createDevTools<
liftedStore?: LiftedStore<S, A, MonitorState>;
static instrument = (options: Options<S, A, MonitorState, MonitorAction>) =>
static instrument = (
options?: Options<S, A, MonitorState, MonitorAction>
) =>
instrument(
(state, action) => Monitor.update(monitorProps, state, action),
options

View File

@ -8,7 +8,7 @@ export default function persistState<
A extends Action<unknown>,
MonitorState
>(
sessionId?: string,
sessionId?: string | null,
deserializeState: (state: S) => S = identity,
deserializeAction: (action: A) => A = identity
): StoreEnhancer {

View File

@ -8,6 +8,6 @@
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
// See https://github.com/DefinitelyTyped/DefinitelyTyped/issues/33311
"types": ["node", "jest"]
"types": ["node", "jest", "webpack-env"]
}
}

View File

@ -3408,6 +3408,11 @@
"@types/serve-static" "*"
"@types/webpack" "*"
"@types/webpack-env@^1.15.2":
version "1.15.2"
resolved "https://registry.yarnpkg.com/@types/webpack-env/-/webpack-env-1.15.2.tgz#927997342bb9f4a5185a86e6579a0a18afc33b0a"
integrity sha512-67ZgZpAlhIICIdfQrB5fnDvaKFcDxpKibxznfYRVAT4mQE41Dido/3Ty+E3xGBmTogc5+0Qb8tWhna+5B8z1iQ==
"@types/webpack-sources@*":
version "1.4.2"
resolved "https://registry.yarnpkg.com/@types/webpack-sources/-/webpack-sources-1.4.2.tgz#5d3d4dea04008a779a90135ff96fb5c0c9e6292c"