UNPKG

@zohodesk/hooks

Version:

Unified Component Library - Hooks

122 lines (113 loc) 2.73 kB
import { useEffect } from 'react'; import useCommonReducer from "../utils/useCommonReducer"; import multiSelectStateReducer from "./multiSelectStateReducer"; import * as constants from "./constants"; import { isArrayContainsOption } from "./utils/actions"; /** * @param {} {selectedOptions=[] * @param {} list=[]} * @param {} customReducer */ export default function useMultiselect() { let props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; let customReducer = arguments.length > 1 ? arguments[1] : undefined; const { selectedOptions = [], list = [] } = props; const { state, dispatch } = useCommonReducer(multiSelectStateReducer, customReducer, { list, selectedOptions, filteredOptions: [], searchString: '' }); useEffect(() => { if (list.length > 0) { dispatch({ type: constants.UPDATE_FILTERED_OPTIONS, data: { selectedOptions: state.selectedOptions, list: state.list } }); } }, []); function addOption(opt) { dispatch({ type: constants.ADD, data: { option: opt, filteredOptions: state.filteredOptions, list: state.list } }); } function handleSelect(opt) { dispatch({ type: constants.SELECT, data: { option: opt, selectedOptions: state.selectedOptions, filteredOptions: state.filteredOptions } }); } function handleRemove(opt) { dispatch({ type: constants.REMOVE, data: { option: opt, selectedOptions: state.selectedOptions, list: state.list } }); } function handleSelectAll() { dispatch({ type: constants.SELECT_ALL, data: { selectedOptions: state.selectedOptions, list: state.list } }); } function handleRemoveAll() { dispatch({ type: constants.REMOVE_ALL, data: { list: state.list } }); } function handleSearch(str) { let key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'value'; dispatch({ type: constants.SEARCH, data: { searchString: str, searchKey: key, selectedOptions: state.selectedOptions, list: state.list } }); } function filterOptionsCheck(opt) { return isArrayContainsOption(opt, state.filteredOptions); } return { addOption, handleSelect, handleRemove, handleSelectAll, handleRemoveAll, handleSearch, filterOptionsCheck, searchString: state.searchString, list: state.list, selectedOptions: state.selectedOptions, filteredOptions: state.filteredOptions }; }