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

86 lines
2.6 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,
highlighted: action.highlighted,
disabled: action.disabled,
selected: false,
active: true,
}];
case 'HIGHLIGHT_OPTION':
return state.map((option) => {
if(option.id === parseInt(action.id)) {
option.highlighted = true;
} else {
option.highlighted = false;
}
return option;
});
case 'SELECT_OPTION':
return state.map((option) => {
if(option.id === parseInt(action.id)) {
option.selected = action.selected;
}
return option;
});
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 = action.selected;
}
return option;
});
} else {
return state;
}
case 'FILTER_OPTIONS':
const filteredResults = action.results.items;
2016-04-27 17:41:30 +02:00
let firstActive = false;
const newState = state.map((option, index) => {
// Set active state based on whether option is
// within filtered results
option.active = filteredResults.some((result) => {
return result.id === index;
2016-04-14 15:43:36 +02:00
});
2016-04-27 17:41:30 +02:00
// Highlight option if it is active and is the first
// active option in state
if(option.active && firstActive === false) {
option.highlighted = true;
firstActive = true;
} else {
option.highlighted = false;
}
return option;
});
return newState;
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;