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

106 lines
2.7 KiB
JavaScript
Raw Normal View History

const choices = (state = [], action) => {
switch (action.type) {
case 'ADD_CHOICE': {
/*
A disabled choice appears in the choice dropdown but cannot be selected
A selected choice has been added to the passed input's value (added as an item)
An active choice appears within the choice dropdown
*/
return [...state, {
id: action.id,
elementId: action.elementId,
groupId: action.groupId,
value: action.value,
2017-06-27 16:54:22 +02:00
label: (action.label || action.value),
2017-06-27 17:30:08 +02:00
disabled: (action.disabled || false),
selected: false,
active: true,
score: 9999,
2017-07-19 19:48:46 +02:00
customProperties: action.customProperties,
2017-08-02 15:05:26 +02:00
placeholder: (action.placeholder || false),
2017-08-15 10:29:42 +02:00
keyCode: null,
}];
}
case 'ADD_ITEM': {
let newState = state;
2016-07-13 22:40:59 +02:00
// If all choices need to be activated
if (action.activateOptions) {
2017-08-15 10:29:42 +02:00
newState = state.map((obj) => {
const choice = obj;
choice.active = action.active;
return choice;
});
}
// 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) {
2017-08-15 10:29:42 +02:00
newState = state.map((obj) => {
const choice = obj;
if (choice.id === parseInt(action.choiceId, 10)) {
choice.selected = true;
}
return choice;
});
}
return newState;
}
2016-07-13 22:40:59 +02:00
case 'REMOVE_ITEM': {
// 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) {
2017-08-15 10:29:42 +02:00
return state.map((obj) => {
const choice = obj;
if (choice.id === parseInt(action.choiceId, 10)) {
choice.selected = false;
}
return choice;
});
}
return state;
}
2016-08-14 23:14:37 +02:00
case 'FILTER_CHOICES': {
const filteredResults = action.results;
2017-08-15 10:29:42 +02:00
const filteredState = state.map((obj) => {
const choice = obj;
// Set active state based on whether choice is
// within filtered results
choice.active = filteredResults.some((result) => {
if (result.item.id === choice.id) {
choice.score = result.score;
return true;
}
return false;
});
return choice;
});
return filteredState;
}
case 'ACTIVATE_CHOICES': {
2017-08-15 10:29:42 +02:00
return state.map((obj) => {
const choice = obj;
choice.active = action.active;
return choice;
});
}
2016-04-14 15:43:36 +02:00
2016-09-26 18:11:32 +02:00
case 'CLEAR_CHOICES': {
2017-08-15 10:29:42 +02:00
return [];
2016-09-26 18:11:32 +02:00
}
default: {
return state;
}
}
2016-08-14 23:14:37 +02:00
};
2016-09-24 12:07:48 +02:00
export default choices;