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

const DEFAULT_STATE = {
  searchInput: '',
  searchResults: [
    { type: 's', value: '18561' },
  ],
  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':
      return {
        ...state,
        searchInput: action.typedValue,
        searchResults: getSearchResults(action.typedValue),
      };
    case 'SEARCH/FOCUS_CHANGE':
      return {
        ...state,
        hasFocus: action.hasFocus,
      };
    default:
      return state;
  }
};

export default search;