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

76 lines
2.3 KiB
JavaScript
Raw Normal View History

const options = (state = [], action) => {
switch (action.type) {
2016-04-12 15:31:07 +02:00
case 'ADD_OPTION':
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':
// When an item is added and it has an associated option,
// we want to disable it so it can't be chosen again
if(action.optionId > -1) {
return state.map((option) => {
if(option.id === parseInt(action.optionId)) {
option.selected = true;
}
return option;
});
} else {
return state;
}
case 'REMOVE_ITEM':
// When an item is removed and it has an associated option,
// we want to re-enable it so it can be chosen again
if(action.optionId > -1) {
return state.map((option) => {
if(option.id === parseInt(action.optionId)) {
option.selected = false;
}
return option;
});
} else {
return state;
}
case 'FILTER_OPTIONS':
2016-05-03 15:55:38 +02:00
const filteredResults = action.results;
const filteredState = state.map((option, index) => {
// Set active state based on whether option is
// within filtered results
2016-05-02 23:21:34 +02:00
option.active = filteredResults.some((result) => {
2016-05-03 15:55:38 +02:00
if(result.item.id === option.id) {
option.score = result.score;
return true;
}
2016-04-14 15:43:36 +02:00
});
return option;
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_OPTIONS':
return state.map((option) => {
option.active = action.active;
return option;
});
2016-04-14 15:43:36 +02:00
default:
return state;
}
}
export default options;