~cytrogen/masto-fe

ref: e9a181c52c2a701a1f93782233111c234dab5342 masto-fe/app/javascript/mastodon/store/middlewares/loading_bar.ts -rw-r--r-- 1.2 KiB
e9a181c5 — Claire Merge commit 'e95d25e1013b6328457b81bd98e8d6a841d45ec2' into glitch-soc/merge-upstream 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { showLoading, hideLoading } from 'react-redux-loading-bar';
import type { AnyAction, Middleware } from 'redux';

import type { RootState } from '..';

interface Config {
  promiseTypeSuffixes?: string[];
}

const defaultTypeSuffixes: Config['promiseTypeSuffixes'] = [
  'PENDING',
  'FULFILLED',
  'REJECTED',
];

export const loadingBarMiddleware = (
  config: Config = {},
): Middleware<unknown, RootState> => {
  const promiseTypeSuffixes = config.promiseTypeSuffixes ?? defaultTypeSuffixes;

  return ({ dispatch }) =>
    (next) =>
    (action: AnyAction) => {
      if (action.type && !action.skipLoading) {
        const [PENDING, FULFILLED, REJECTED] = promiseTypeSuffixes;

        const isPending = new RegExp(`${PENDING}$`, 'g');
        const isFulfilled = new RegExp(`${FULFILLED}$`, 'g');
        const isRejected = new RegExp(`${REJECTED}$`, 'g');

        if (typeof action.type === 'string') {
          if (action.type.match(isPending)) {
            dispatch(showLoading());
          } else if (
            action.type.match(isFulfilled) ??
            action.type.match(isRejected)
          ) {
            dispatch(hideLoading());
          }
        }
      }

      return next(action);
    };
};