From 6ec8894d44490e998a3f7a9b47697858c15c238f Mon Sep 17 00:00:00 2001 From: przeq piciel Date: Fri, 18 Oct 2024 20:29:57 +0000 Subject: [PATCH] added key events to popup component --- .../FilesEditor/AddDocument/index.tsx | 13 ++++++-- app/components/Popup/index.tsx | 32 +++++++++++++++---- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/app/components/FilesEditor/AddDocument/index.tsx b/app/components/FilesEditor/AddDocument/index.tsx index 084b17d..43193aa 100644 --- a/app/components/FilesEditor/AddDocument/index.tsx +++ b/app/components/FilesEditor/AddDocument/index.tsx @@ -1,9 +1,8 @@ "use client"; -import React from "react"; +import React, { useState, useRef } from "react"; import AddDocumentIcon from "@/components/Icons/AddDocument"; import Popup from "@/components/Popup"; -import { useState } from "react"; import Pterodactyl from "@/components/Pterodactyl"; import { useSearchParams } from "next/navigation"; @@ -14,11 +13,18 @@ const Index = () => { const serverId = urlParams.get("serverid") || ""; const pathParam = urlParams.get("path") || "/"; const apiKey = `${process.env.NEXT_PUBLIC_API_KEY}`; + const inputRef = useRef(null); const pterodactyl = new Pterodactyl(); function togglePopup() { setShowPopup(!showPopup); + if (!showPopup) { + // set focus on input + setTimeout(() => { + inputRef.current?.focus(); + }, 100); + } } function handleOk() { @@ -42,6 +48,7 @@ const Index = () => { >
{ className="btn btn-sm" > - Add Document + Add Document ); diff --git a/app/components/Popup/index.tsx b/app/components/Popup/index.tsx index 1b242df..dc7f855 100644 --- a/app/components/Popup/index.tsx +++ b/app/components/Popup/index.tsx @@ -1,6 +1,6 @@ "use client"; -import React from "react"; +import React, { useEffect } from "react"; interface PopupProps extends React.HTMLAttributes { show?: boolean; @@ -14,8 +14,31 @@ const Popup: React.FC = ({ show = false, title, children, + onClickClose, + onClickOk, ...props }) => { + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape" && onClickClose) { + onClickClose(event as unknown as React.MouseEvent); + } + if (event.key === "Enter") { + if (onClickOk) { + onClickOk(event as unknown as React.MouseEvent); + } + } + }; + + if (show) { + window.addEventListener("keydown", handleKeyDown); + } + + return () => { + window.removeEventListener("keydown", handleKeyDown); + }; + }, [show, onClickClose]); + if (!show) return null; return ( @@ -30,13 +53,10 @@ const Popup: React.FC = ({ )} {children}
- -