Choices/assets/scripts/src/reducers/choices.js

77 lines
2.6 KiB
JavaScript
Raw Normal View History

2016-06-29 15:47:58 +02:00
import { sortByAlpha } from './../lib/utils.js';
const choices = (state = [], action) => {
switch (action.type) {
case 'ADD_CHOICE':
2016-04-14 15:43:36 +02:00
return [...state, {
id: action.id,
groupId: action.groupId,
2016-04-12 15:31:07 +02:00
value: action.value,
label: action.label,
disabled: action.disabled, // A disabled choice appears in the choice dropdown but cannot be selected
selected: false, // A selected choice has been added to the passed input's value (added as an item)
active: true, // An active choice appears within the choice dropdown
2016-05-03 15:55:38 +02:00
score: 9999,
2016-06-29 15:47:58 +02:00
}].sort(sortByAlpha);
case 'ADD_ITEM':
2016-06-27 15:57:33 +02:00
// When an item is added and it has an associated choice,
// we want to disable it so it can't be chosen again
if(action.choiceId > -1) {
2016-06-27 15:57:33 +02:00
return state.map((choice) => {
if(choice.id === parseInt(action.choiceId)) {
choice.selected = true;
}
2016-06-27 15:57:33 +02:00
return choice;
});
} else {
return state;
}
case 'REMOVE_ITEM':
2016-06-27 15:57:33 +02:00
// When an item is removed and it has an associated choice,
// we want to re-enable it so it can be chosen again
if(action.choiceId > -1) {
2016-06-27 15:57:33 +02:00
return state.map((choice) => {
if(choice.id === parseInt(action.choiceId)) {
choice.selected = false;
}
2016-06-27 15:57:33 +02:00
return choice;
});
} else {
return state;
}
case 'FILTER_CHOICES':
2016-05-03 15:55:38 +02:00
const filteredResults = action.results;
2016-06-27 15:57:33 +02:00
const filteredState = state.map((choice, index) => {
// Set active state based on whether choice is
// within filtered results
2016-05-02 23:21:34 +02:00
2016-06-27 15:57:33 +02:00
choice.active = filteredResults.some((result) => {
if(result.item.id === choice.id) {
choice.score = result.score;
2016-05-03 15:55:38 +02:00
return true;
}
2016-04-14 15:43:36 +02:00
});
2016-06-27 15:57:33 +02:00
return choice;
2016-05-03 15:55:38 +02:00
}).sort((prev, next) => {
return prev.score - next.score;
});
2016-05-03 15:55:38 +02:00
return filteredState;
case 'ACTIVATE_CHOICES':
2016-06-27 15:57:33 +02:00
return state.map((choice) => {
choice.active = action.active;
return choice;
2016-06-29 15:47:58 +02:00
}).sort(sortByAlpha);
2016-04-14 15:43:36 +02:00
default:
return state;
}
}
export default choices;