| 1 |
/** |
| 2 |
* Internal dependencies. |
| 3 |
*/ |
| 4 |
import { getArgsWithoutConstraints } from './utilities'; |
| 5 |
|
| 6 |
/** |
| 7 |
* Reducer function. |
| 8 |
* |
| 9 |
* @param {object} state Current state. |
| 10 |
* @param {object} action Action data. |
| 11 |
* @returns {object} Updated state. |
| 12 |
*/ |
| 13 |
export default (state, action) => { |
| 14 |
const newState = { ...state, isPoppingState: false }; |
| 15 |
|
| 16 |
switch (action.type) { |
| 17 |
case 'CLEAR_CONSTRAINTS': { |
| 18 |
const clearedArgs = getArgsWithoutConstraints(newState.args, newState.argsSchema); |
| 19 |
|
| 20 |
newState.args = clearedArgs; |
| 21 |
newState.args.offset = 0; |
| 22 |
|
| 23 |
break; |
| 24 |
} |
| 25 |
case 'CLEAR_RESULTS': { |
| 26 |
newState.aggregations = {}; |
| 27 |
newState.searchResults = []; |
| 28 |
newState.totalResults = 0; |
| 29 |
break; |
| 30 |
} |
| 31 |
case 'SEARCH': { |
| 32 |
newState.args = { ...newState.args, ...action.args, offset: 0 }; |
| 33 |
newState.isOn = true; |
| 34 |
break; |
| 35 |
} |
| 36 |
case 'SEARCH_FOR': { |
| 37 |
const clearedArgs = getArgsWithoutConstraints(newState.args, newState.argsSchema); |
| 38 |
|
| 39 |
newState.args = clearedArgs; |
| 40 |
newState.args.search = action.searchTerm; |
| 41 |
newState.args.offset = 0; |
| 42 |
newState.isOn = true; |
| 43 |
|
| 44 |
break; |
| 45 |
} |
| 46 |
case 'SET_IS_LOADING': { |
| 47 |
newState.isLoading = action.isLoading; |
| 48 |
break; |
| 49 |
} |
| 50 |
case 'TURN_OFF': { |
| 51 |
newState.args = { ...newState.args }; |
| 52 |
newState.isOn = false; |
| 53 |
break; |
| 54 |
} |
| 55 |
case 'SET_RESULTS': { |
| 56 |
const { |
| 57 |
hits: { hits, total }, |
| 58 |
aggregations, |
| 59 |
suggest, |
| 60 |
} = action.response; |
| 61 |
|
| 62 |
newState.isFirstSearch = false; |
| 63 |
|
| 64 |
/** |
| 65 |
* Total number of items. |
| 66 |
*/ |
| 67 |
const totalNumber = typeof total === 'number' ? total : total.value; |
| 68 |
|
| 69 |
newState.aggregations = aggregations; |
| 70 |
newState.searchResults = hits; |
| 71 |
newState.searchTerm = newState.args.search; |
| 72 |
newState.totalResults = totalNumber; |
| 73 |
newState.suggestedTerms = suggest?.ep_suggestion?.[0]?.options || []; |
| 74 |
|
| 75 |
break; |
| 76 |
} |
| 77 |
case 'NEXT_PAGE': { |
| 78 |
newState.args.offset += newState.args.per_page; |
| 79 |
break; |
| 80 |
} |
| 81 |
case 'PREVIOUS_PAGE': { |
| 82 |
newState.args.offset = Math.max(newState.args.offset - newState.args.per_page, 0); |
| 83 |
break; |
| 84 |
} |
| 85 |
case 'POP_STATE': { |
| 86 |
const { isOn, args } = action.args; |
| 87 |
|
| 88 |
newState.args = args; |
| 89 |
newState.isOn = isOn; |
| 90 |
newState.isPoppingState = true; |
| 91 |
|
| 92 |
break; |
| 93 |
} |
| 94 |
default: |
| 95 |
break; |
| 96 |
} |
| 97 |
|
| 98 |
return newState; |
| 99 |
}; |
| 100 |
|