UNPKG

ivue-material-plus

Version:

A high quality UI components Library with Vue.js

114 lines (111 loc) 3.53 kB
import { shallowRef, watch, onMounted, onUpdated } from 'vue'; import { useEventListener } from '@vueuse/core'; import { EVENT_CODE } from '../../../utils/helpers.mjs'; const useKeydown = (el, store) => { const treeItems = shallowRef([]); const checkboxItems = shallowRef([]); const initTabIndex = () => { var _a; treeItems.value = Array.from( el.value.querySelectorAll(".is-focusable[role=treeItem]") ); checkboxItems.value = Array.from( el.value.querySelectorAll("input[type=checkbox]") ); const checkedItem = el.value.querySelectorAll(".is-checked[role=treeItem]"); if (checkedItem.length) { checkedItem[0].setAttribute("tabindex", "0"); return; } (_a = treeItems.value[0]) == null ? void 0 : _a.setAttribute("tabindex", "0"); }; const handleKeydown = (event) => { const currentItem = event.target; if (!currentItem.className.includes("ivue-tree-node")) { return; } const code = event.code; treeItems.value = Array.from( el.value.querySelectorAll(".is-focusable[role=treeItem]") ); const currentIndex = treeItems.value.indexOf(currentItem); let nextIndex; if ([EVENT_CODE.up, EVENT_CODE.down].includes(code)) { event.preventDefault(); if (code === EVENT_CODE.up) { if (currentIndex === -1) { nextIndex = 0; } else if (currentIndex !== 0) { nextIndex = currentIndex - 1; } else { nextIndex = treeItems.value.length - 1; } const startIndex = nextIndex; treeItems.value.forEach(() => { if (store.value.getNode(treeItems.value[nextIndex].dataset.key).canFocus) { return; } nextIndex--; if (nextIndex === startIndex) { nextIndex = -1; return; } if (nextIndex < 0) { nextIndex = treeItems.value.length - 1; } }); } else { if (currentIndex === -1) { nextIndex = 0; } else if (currentIndex < treeItems.value.length - 1) { nextIndex = currentIndex + 1; } else { nextIndex = 0; } const startIndex = nextIndex; treeItems.value.forEach(() => { if (store.value.getNode(treeItems.value[nextIndex].dataset.key).canFocus) { return; } nextIndex++; if (nextIndex === startIndex) { nextIndex = -1; return; } if (nextIndex >= treeItems.value.length) { nextIndex = 0; } }); } nextIndex !== -1 && treeItems.value[nextIndex].focus(); } if ([EVENT_CODE.left, EVENT_CODE.right].includes(code)) { event.preventDefault(); currentItem.click(); } const hasInput = currentItem.querySelector( '[type="checkbox"]' ); if ([EVENT_CODE.enter, EVENT_CODE.space].includes(code) && hasInput) { event.preventDefault(); hasInput.click(); } }; watch(checkboxItems, (value) => { value.forEach((checkbox) => { checkbox.setAttribute("tabindex", "-1"); }); }); onMounted(() => { initTabIndex(); useEventListener(el, "keydown", handleKeydown); }); onUpdated(() => { treeItems.value = Array.from(el.value.querySelectorAll("[role=treeItem]")); checkboxItems.value = Array.from( el.value.querySelectorAll("input[type=checkbox]") ); }); }; export { useKeydown }; //# sourceMappingURL=useKeydown.mjs.map