UNPKG

winbox-ui-next

Version:

We Design Vue 2.0: A Vue.js 3 UI Library

88 lines (87 loc) 2.97 kB
import { ref, watch } from "vue"; import { getRelativeRect } from "../_utils/dom.js"; import { getOptionNodes } from "../_components/dropdown/utils.js"; const useOptions = ({ options, extraOptions, inputValue, filterOption, showExtraOptions, dropdownRef, optionRefs, virtualListRef }) => { const optionInfoMap = new Map(); const enabledOptionSet = new Set(); const activeOption = ref(); const getNextActiveOption = (direction) => { const enabledOptions = Array.from(enabledOptionSet); const _length = enabledOptions.length; if (_length === 0) { return void 0; } if (!activeOption.value) { if (direction === "down") { return optionInfoMap.get(enabledOptions[0]); } return optionInfoMap.get(enabledOptions[_length - 1]); } const activeIndex = enabledOptions.indexOf(activeOption.value.value); const nextIndex = (_length + activeIndex + (direction === "up" ? -1 : 1)) % _length; return optionInfoMap.get(enabledOptions[nextIndex]); }; const scrollIntoView = (value) => { var _a, _b; if (virtualListRef == null ? void 0 : virtualListRef.value) { virtualListRef.value.scrollTo({ key: value }); } const wrapperEle = (_b = (_a = dropdownRef == null ? void 0 : dropdownRef.value) == null ? void 0 : _a.$refs) == null ? void 0 : _b.wrapperRef; const optionEle = optionRefs == null ? void 0 : optionRefs.value[value]; if (!wrapperEle || !optionEle) { return; } if (wrapperEle.scrollHeight === wrapperEle.offsetHeight) { return; } const optionRect = getRelativeRect(optionEle, wrapperEle); const wrapperScrollTop = wrapperEle.scrollTop; if (optionRect.top < 0) { wrapperEle.scrollTo(0, wrapperScrollTop + optionRect.top); } else if (optionRect.bottom < 0) { wrapperEle.scrollTo(0, wrapperScrollTop - optionRect.bottom); } }; const nodes = ref([]); const setOptionNodes = () => { var _a; nodes.value = getOptionNodes({ options: options == null ? void 0 : options.value, extraOptions: extraOptions == null ? void 0 : extraOptions.value, inputValue: inputValue == null ? void 0 : inputValue.value, filterOption: filterOption == null ? void 0 : filterOption.value, showExtraOptions: (_a = showExtraOptions == null ? void 0 : showExtraOptions.value) != null ? _a : true, optionInfoMap, enabledOptionSet }); if (enabledOptionSet.size > 0 && (!activeOption.value || !enabledOptionSet.has(activeOption.value.value))) { const enabledOptions = Array.from(enabledOptionSet); activeOption.value = optionInfoMap.get(enabledOptions[0]); } }; watch([options, extraOptions, inputValue, filterOption], () => { setOptionNodes(); }, { immediate: true }); return { nodes, optionInfoMap, enabledOptionSet, activeOption, getNextActiveOption, scrollIntoView }; }; export { useOptions };