OnKeyDown в react приложении срабатывает только один раз

Всем привет. Я новичок в web dev. Никак не могу понять проблему. Моя задача заключается в изменении частей инпута (день и месяц) при нажатии комбинации ctr + ArrowUp(прибавляет) и ctr + ArrowDown(убавляет). При этом изменяемая часть выделяется - это достигается отслеживанием позиции курсора (selectionStart). Код работает, но почему-то при нажатии необходимой комбинации и выполнения условий положения курсора OnKeyDown отрабатывает только один раз последующие нажатия прибавления или убавления не дают результата. Почему так происходит? Как заставить событие работать при каждом нажатии комбинации?

SANDBOX SNIPPET

Мой код

import React, { useState, useEffect, useRef } from "react";
import styles from "./DataInput.module.css";

const cur_date = new Date();

const DataInput = () => {
  const inputEl = useRef();
  const [selection, setSelection] = useState();
  const [currentDate, newCurrentDate] = useState();

  const date_format = cur_date
    .toLocaleString()
    .replaceAll(".", "/")
    .replace(",", "");

  const [value, setValue] = useState(date_format);

  useEffect(() => {
    if (!selection) return; // prevent running on start
    const { start, end } = selection;
    inputEl.current.focus();
    inputEl.current.setSelectionRange(start, end);
  }, [selection]);

  const keyHandler = (e) => {
    if (e.ctrlKey && e.key === "ArrowUp") {
      e.preventDefault();
      if (
        inputEl.current.selectionStart > 0 &&
        inputEl.current.selectionStart < 2
      ) {
        setSelection({ start: 0, end: 2 });
        const newDay = cur_date.setDate(cur_date.getDate() + 1);
        setValue(
          new Date(newDay)
            .toLocaleString()
            .replaceAll(".", "/")
            .replace(",", "")
        );
      }
      if (
        inputEl.current.selectionStart > 3 &&
        inputEl.current.selectionStart < 5
      ) {
        setSelection({ start: 3, end: 5 });
        const newMonth = cur_date.setMonth(cur_date.getMonth() + 1);
        setValue(
          new Date(newMonth)
            .toLocaleString()
            .replaceAll(".", "/")
            .replace(",", "")
        );
      }
    }
    if (e.ctrlKey && e.key === "ArrowDown") {
      e.preventDefault();
      if (
        inputEl.current.selectionStart > 0 &&
        inputEl.current.selectionStart < 2
      ) {
        setSelection({ start: 0, end: 2 });
        let newDate = cur_date.setDate(cur_date.getDate() - 1);
        setValue(
          new Date(newDate)
            .toLocaleString()
            .replaceAll(".", "/")
            .replace(",", "")
        );
      }
      if (
        inputEl.current.selectionStart > 3 &&
        inputEl.current.selectionStart < 5
      ) {
        setSelection({ start: 3, end: 5 });
        const newMonth = cur_date.setMonth(cur_date.getMonth() - 1);
        setValue(
          new Date(newMonth)
            .toLocaleString()
            .replaceAll(".", "/")
            .replace(",", "")
        );
      }
    }
  };

  const changeHandler = (e) => {
    setValue(e.target.value);
  };

  return (
    <div className={styles.main}>
      <h1> Frontend Task</h1>
      <p id="name">Abramov David</p>
      <input
        ref={inputEl}
        value={value}
        onChange={changeHandler}
        onKeyDown={keyHandler}
      />
    </div>
  );
};

export default DataInput;

Ответы (0 шт):