mastodon/app/javascript/mastodon/store/middlewares/loading_bar.ts

43 lines
1.1 KiB
TypeScript
Raw Normal View History

2017-01-16 06:27:58 -06:00
import { showLoading, hideLoading } from 'react-redux-loading-bar';
import { Middleware } from 'redux';
import { RootState } from '..';
2017-01-16 06:27:58 -06:00
interface Config {
promiseTypeSuffixes?: string[];
}
const defaultTypeSuffixes: Config['promiseTypeSuffixes'] = [
'PENDING',
'FULFILLED',
'REJECTED',
];
2017-01-16 06:27:58 -06:00
export const loadingBarMiddleware = (
config: Config = {}
): Middleware<Record<string, never>, RootState> => {
2017-01-16 06:27:58 -06:00
const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypeSuffixes;
return ({ dispatch }) =>
(next) =>
(action) => {
if (action.type && !action.skipLoading) {
const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes;
2017-01-16 06:27:58 -06:00
const isPending = new RegExp(`${PENDING}$`, 'g');
const isFulfilled = new RegExp(`${FULFILLED}$`, 'g');
const isRejected = new RegExp(`${REJECTED}$`, 'g');
2017-01-16 06:27:58 -06:00
if (action.type.match(isPending)) {
dispatch(showLoading());
} else if (
action.type.match(isFulfilled) ||
action.type.match(isRejected)
) {
dispatch(hideLoading());
}
2017-01-16 06:27:58 -06:00
}
return next(action);
};
};