|
| 1 | +import { c } from "helpers/StylesHelper"; |
| 2 | +import { KeyboardEventHandler } from "react"; |
| 3 | + |
| 4 | +type TabIndexElement = HTMLDivElement | HTMLSpanElement; |
| 5 | + |
| 6 | +const onKeyDownArrowKeys: KeyboardEventHandler<HTMLDivElement> = (event) => { |
| 7 | + const currentInput = activeDocument.activeElement; |
| 8 | + if (currentInput === null || !currentInput.classList.contains(c('tabIndex'))) return; |
| 9 | + |
| 10 | + const currentTd = currentInput.parentElement; |
| 11 | + const currentTr = currentTd.parentElement; |
| 12 | + const index = Array.from(currentTr.children).indexOf(currentTd); |
| 13 | + |
| 14 | + switch (event.key) { |
| 15 | + case "ArrowLeft": |
| 16 | + // Left pressed |
| 17 | + const TdLeft = currentTd.previousElementSibling; |
| 18 | + if (!TdLeft) break; |
| 19 | + const TdLeftTabIndex = TdLeft.getElementsByClassName(c('tabIndex'))[0] as TabIndexElement; |
| 20 | + if (!TdLeftTabIndex) break; |
| 21 | + TdLeftTabIndex.focus(); |
| 22 | + break; |
| 23 | + case "ArrowRight": |
| 24 | + // Right pressed |
| 25 | + const TdRight = currentTd.nextElementSibling; |
| 26 | + if (!TdRight) break; |
| 27 | + const TdRightTabIndex = TdRight.getElementsByClassName(c('tabIndex'))[0] as TabIndexElement; |
| 28 | + if (!TdRightTabIndex) break; |
| 29 | + TdRightTabIndex.focus(); |
| 30 | + break; |
| 31 | + case "ArrowUp": |
| 32 | + // Up pressed |
| 33 | + const TrUp = currentTr |
| 34 | + .previousElementSibling |
| 35 | + ?.children; |
| 36 | + if (!TrUp) break; |
| 37 | + |
| 38 | + const TdUp = (Array.from(TrUp)[index] |
| 39 | + .getElementsByClassName(c('tabIndex'))[0] as TabIndexElement); |
| 40 | + |
| 41 | + if (!TdUp) break; |
| 42 | + TdUp.focus(); |
| 43 | + break; |
| 44 | + case "ArrowDown": |
| 45 | + // Down pressed |
| 46 | + const TrDown = currentTr |
| 47 | + .nextElementSibling |
| 48 | + ?.children; |
| 49 | + if (TrDown === undefined) break; |
| 50 | + |
| 51 | + const TdDown = (Array.from(TrDown)[index] |
| 52 | + .getElementsByClassName(c('tabIndex'))[0] as TabIndexElement); |
| 53 | + |
| 54 | + if (TdDown === undefined) break; |
| 55 | + TdDown.focus(); |
| 56 | + break; |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +export default onKeyDownArrowKeys; |
0 commit comments