From 5e1eb7bd72fa8778318f1ae87dbabfe05acf4d71 Mon Sep 17 00:00:00 2001 From: Shubham kumar <106580067+SksOp@users.noreply.github.com> Date: Tue, 23 May 2023 13:09:56 +0530 Subject: [PATCH] fixes:keyboard-navigation-8887' (#9006) --- .../schedules/components/Schedule.tsx | 63 ++++++++++++++++++- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/packages/features/schedules/components/Schedule.tsx b/packages/features/schedules/components/Schedule.tsx index 6cc732e6fb..7045c1eb74 100644 --- a/packages/features/schedules/components/Schedule.tsx +++ b/packages/features/schedules/components/Schedule.tsx @@ -1,4 +1,4 @@ -import { Fragment, useCallback, useEffect, useMemo, useState } from "react"; +import { Fragment, useCallback, useEffect, useMemo, useState, useRef } from "react"; import type { ArrayPath, Control, @@ -382,6 +382,38 @@ const CopyTimes = ({ }) => { const [selected, setSelected] = useState([]); const { i18n, t } = useLocale(); + const itteratablesByKeyRef = useRef<(HTMLInputElement | HTMLButtonElement)[]>([]); + useEffect(() => { + document.addEventListener("keydown", handleKeyDown); + return () => { + document.removeEventListener("keydown", handleKeyDown); + }; + }, []); + const handleKeyDown = (event: KeyboardEvent) => { + const itteratables = itteratablesByKeyRef.current; + const isActionRequired = + event.key === "Tab" || event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "Enter"; + if (!isActionRequired || !itteratables.length) return; + event.preventDefault(); + const currentFocused = document.activeElement as HTMLInputElement | HTMLButtonElement; + let currentIndex = itteratables.findIndex((checkbox) => checkbox === currentFocused); + if (event.key === "Enter") { + if (currentIndex === -1) return; + currentFocused.click(); + return; + } + if (currentIndex === -1) { + itteratables[0].focus(); + } else { + // Move focus based on the arrow key pressed + if (event.key === "ArrowUp") { + currentIndex = (currentIndex - 1 + itteratables.length) % itteratables.length; + } else if (event.key === "ArrowDown" || event.key === "Tab") { + currentIndex = (currentIndex + 1) % itteratables.length; + } + itteratables[currentIndex].focus(); + } + }; return (
@@ -402,6 +434,11 @@ const CopyTimes = ({ setSelected([]); } }} + ref={(ref) => { + if (ref) { + itteratablesByKeyRef.current.push(ref as HTMLInputElement); + } + }} /> @@ -423,6 +460,12 @@ const CopyTimes = ({ setSelected(selected.filter((item) => item !== weekdayIndex)); } }} + ref={(ref) => { + if (ref && disabled !== weekdayIndex) { + //we don't need to iterate over disabled elements + itteratablesByKeyRef.current.push(ref as HTMLInputElement); + } + }} /> @@ -432,10 +475,24 @@ const CopyTimes = ({

- -