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

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2017-01-16 07:27:58 -05:00
import { showLoading, hideLoading } from 'react-redux-loading-bar';
import type { AnyAction, Middleware } from 'redux';
import type { RootState } from '..';
2017-01-16 07:27:58 -05:00
interface Config {
promiseTypeSuffixes?: string[];
}
const defaultTypeSuffixes: Config['promiseTypeSuffixes'] = [
'PENDING',
'FULFILLED',
'REJECTED',
];
2017-01-16 07:27:58 -05:00
export const loadingBarMiddleware = (
2023-07-13 05:26:45 -04:00
config: Config = {},
2023-09-12 06:18:19 -04:00
): Middleware<unknown, RootState> => {
const promiseTypeSuffixes = config.promiseTypeSuffixes ?? defaultTypeSuffixes;
2017-01-16 07:27:58 -05:00
return ({ dispatch }) =>
(next) =>
(action: AnyAction) => {
if (action.type && !action.skipLoading) {
const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes;
2017-01-16 07:27:58 -05:00
const isPending = new RegExp(`${PENDING}$`, 'g');
const isFulfilled = new RegExp(`${FULFILLED}$`, 'g');
const isRejected = new RegExp(`${REJECTED}$`, 'g');
2017-01-16 07:27:58 -05:00
if (typeof action.type === 'string') {
if (action.type.match(isPending)) {
dispatch(showLoading());
} else if (
action.type.match(isFulfilled) ??
action.type.match(isRejected)
) {
dispatch(hideLoading());
}
}
2017-01-16 07:27:58 -05:00
}
return next(action);
};
};