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

76 lines
2.3 KiB
JavaScript
Raw Normal View History

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,
selected: false,
active: true,
2016-05-03 15:55:38 +02:00
score: 9999,
}];
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;
2016-06-27 15:57:33 +02:00
return choice;
});
2016-04-14 15:43:36 +02:00
default:
return state;
}
}
export default choices;