aboutsummaryrefslogtreecommitdiff
path: root/src/client/react/reducers/search.js
blob: f566b492822810981e03fa94c4dccf2b18f3050d (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
/* global USERS */
import fuzzy from 'fuzzy';

const DEFAULT_STATE = {
  input: '',
  results: [
    { type: 's', value: '18561' },
  ],
  selectedResult: null,
  isExactMatch: false,
};

function getSearchResults(query) {
  if (query.trim() === '') {
    return [];
  }

  const allResults = fuzzy.filter(query, USERS, {
    extract: user => user.value,
  });

  const firstResults = allResults.splice(0, 4);
  const users = firstResults.map(result => result.original);

  return users;
}

const search = (state = DEFAULT_STATE, action) => {
  switch (action.type) {
    case 'SEARCH/INPUT_CHANGE': {
      let results = getSearchResults(action.typedValue);
      let selectedResult = null;
      let isExactMatch = false;

      // Is the typed value exactly the same as the first result? Then show the
      // appropiate icon instead of the generic search icon.
      if ((results.length > 0) && (action.typedValue === results[0].value)) {
        [selectedResult] = results;
        isExactMatch = true;
        results = results.splice(1);
      }

      return {
        ...state,
        input: action.typedValue,
        results,
        selectedResult,
        isExactMatch,
      };
    }
    default:
      return state;
  }
};

export default search;