@kelvininc/ui-components
Version:
Kelvin UI Components
44 lines (43 loc) • 2.57 kB
JavaScript
import { EToggleState } from "../../types";
import { ADD_OPTION } from "./select-multi-options.config";
export const buildNewOption = (highlightedOption, createInputPlaceholder) => (Object.assign(Object.assign({}, ADD_OPTION), { label: createInputPlaceholder !== null && createInputPlaceholder !== void 0 ? createInputPlaceholder : ADD_OPTION.label, togglable: false, selected: false, state: EToggleState.None, highlighted: ADD_OPTION.value === highlightedOption }));
const buildSelectOption = ({ optionKey, options = {}, allOptions = {}, selectedOptions = {}, highlightedOption, level = 0 }) => {
const childrenOptions = buildSelectOptions({
options: options[optionKey].options,
allOptions: allOptions[optionKey].options,
selectedOptions,
highlightedOption,
level: level + 1
});
return Object.assign(Object.assign({ togglable: true }, options[optionKey]), { options: childrenOptions, selected: selectedOptions[optionKey] === true, state: getOptionToggleState(allOptions[optionKey], selectedOptions), highlighted: optionKey === highlightedOption, level: level, heading: Object.values(childrenOptions).length > 0 });
};
const getOptionToggleState = (option, selectedOptions = {}) => {
var _a;
const children = Object.values((_a = option.options) !== null && _a !== void 0 ? _a : {});
if (children.length === 0) {
if (selectedOptions[option.value]) {
return EToggleState.Selected;
}
return EToggleState.None;
}
const childrenStates = children.map(childrenOpt => getOptionToggleState(childrenOpt, selectedOptions));
const [firstChildrenState, ...otherChildrenStates] = childrenStates;
// Check if all children have the same state
if (otherChildrenStates.every(childrenState => childrenState === firstChildrenState)) {
return firstChildrenState;
}
// Otherwise
return EToggleState.Indeterminate;
};
export const buildSelectOptions = ({ options = {}, allOptions = {}, selectedOptions = {}, highlightedOption, hasAddItem = false, createInputPlaceholder, level = 0 }) => {
const selectOptions = Object.keys(options).reduce((accumulator, optionKey) => {
if (allOptions[optionKey]) {
accumulator[optionKey] = buildSelectOption({ optionKey, options, allOptions, selectedOptions, highlightedOption, level });
}
return accumulator;
}, {});
if (hasAddItem) {
selectOptions[ADD_OPTION.value] = buildNewOption(highlightedOption, createInputPlaceholder);
}
return selectOptions;
};