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

const DEFAULT_STATE = {
  input: '',
  results: [
    { type: 's', value: '18561' },
  ],
  exactMatch: null,
  hasFocus: 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 exactMatch = null;

      // 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)) {
        [exactMatch] = results;
        results = results.splice(1);
      }

      return {
        ...state,
        input: action.typedValue,
        results,
        exactMatch,
      };
    }
    case 'SEARCH/FOCUS_CHANGE':
      return {
        ...state,
        hasFocus: action.hasFocus,
      };
    default:
      return state;
  }
};

export default search;