summaryrefslogtreecommitdiff
path: root/src/ducks/rules.js
blob: c38dc6c6c014c0333e5cd2cda29709e9508eb8d7 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import * as rulesAPI from 'a/rules';
import { getClashAPIConfig } from 'd/app';
import invariant from 'invariant';
// import { debounce } from 'lodash-es';
import { createSelector } from 'reselect';

export const getAllRules = s => s.rules.allRules;
export const getSearchText = s => s.rules.searchText;
export const getRules = createSelector(
  getSearchText,
  getAllRules,
  (searchText, allRules) => {
    if (searchText === '') return allRules;
    return allRules.filter(r => r.payload.indexOf(searchText) >= 0);
  }
);

const CompletedFetchRules = 'rules/CompletedFetchRules';
const UpdateSearchText = 'rule/UpdateSearchText';

export function updateSearchText(text) {
  return {
    type: UpdateSearchText,
    payload: { searchText: text.toLowerCase() }
  };
}

export function fetchRules() {
  return async (dispatch, getState) => {
    const apiSetup = getClashAPIConfig(getState());
    const res = await rulesAPI.fetchRules(apiSetup);
    const json = await res.json();
    invariant(
      json.rules && json.rules.length >= 0,
      'there is no valid rules list in the rules API response'
    );

    // attach an id
    const allRules = json.rules.map((r, i) => {
      r.id = i;
      return r;
    });

    dispatch({
      type: CompletedFetchRules,
      payload: { allRules }
    });
  };
}

export function fetchRulesOnce() {
  return async (dispatch, getState) => {
    const allRules = getAllRules(getState());
    if (allRules.length === 0) return await dispatch(fetchRules());
  };
}

// {"type":"FINAL","payload":"","proxy":"Proxy"}
// {"type":"IPCIDR","payload":"172.16.0.0/12","proxy":"DIRECT"}
const initialState = {
  // filteredRules: [],
  allRules: [],
  searchText: ''
};

export default function reducer(state = initialState, { type, payload }) {
  switch (type) {
    case UpdateSearchText:
    case CompletedFetchRules: {
      return { ...state, ...payload };
    }

    default:
      return state;
  }
}