prevent enter key on Link selector to trigger modal submit

This commit is contained in:
Palanikannan1437 2023-08-17 21:56:32 +05:30
parent ab6bf6aba0
commit 1633765ebb

View File

@ -1,6 +1,6 @@
import { Editor } from "@tiptap/core"; import { Editor } from "@tiptap/core";
import { Check, Trash } from "lucide-react"; import { Check, Trash } from "lucide-react";
import { Dispatch, FC, SetStateAction, useEffect, useRef } from "react"; import { Dispatch, FC, SetStateAction, useCallback, useEffect, useRef } from "react";
import { cn } from "../utils"; import { cn } from "../utils";
import isValidHttpUrl from "./utils/link-validator"; import isValidHttpUrl from "./utils/link-validator";
interface LinkSelectorProps { interface LinkSelectorProps {
@ -9,9 +9,19 @@ interface LinkSelectorProps {
setIsOpen: Dispatch<SetStateAction<boolean>>; setIsOpen: Dispatch<SetStateAction<boolean>>;
} }
export const LinkSelector: FC<LinkSelectorProps> = ({ editor, isOpen, setIsOpen }) => { export const LinkSelector: FC<LinkSelectorProps> = ({ editor, isOpen, setIsOpen }) => {
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const onLinkSubmit = useCallback(() => {
const input = inputRef.current;
const url = input?.value;
if (url && isValidHttpUrl(url)) {
editor.chain().focus().setLink({ href: url }).run();
setIsOpen(false);
}
}, [editor, inputRef, setIsOpen]);
useEffect(() => { useEffect(() => {
inputRef.current && inputRef.current?.focus(); inputRef.current && inputRef.current?.focus();
}); });
@ -40,6 +50,11 @@ export const LinkSelector: FC<LinkSelectorProps> = ({ editor, isOpen, setIsOpen
{isOpen && ( {isOpen && (
<div <div
className="fixed top-full z-[99999] mt-1 flex w-60 overflow-hidden rounded border border-custom-border-300 bg-custom-background-100 dow-xl animate-in fade-in slide-in-from-top-1" className="fixed top-full z-[99999] mt-1 flex w-60 overflow-hidden rounded border border-custom-border-300 bg-custom-background-100 dow-xl animate-in fade-in slide-in-from-top-1"
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault(); onLinkSubmit();
}
}}
> >
<input <input
ref={inputRef} ref={inputRef}
@ -62,12 +77,7 @@ export const LinkSelector: FC<LinkSelectorProps> = ({ editor, isOpen, setIsOpen
) : ( ) : (
<button className="flex items-center rounded-sm p-1 text-custom-text-300 transition-all hover:bg-custom-background-90" type="button" <button className="flex items-center rounded-sm p-1 text-custom-text-300 transition-all hover:bg-custom-background-90" type="button"
onClick={() => { onClick={() => {
const input = inputRef.current; onLinkSubmit();
const url = input?.value;
if (url && isValidHttpUrl(url)) {
editor.chain().focus().setLink({ href: url }).run();
setIsOpen(false);
}
}} }}
> >
<Check className="h-4 w-4" /> <Check className="h-4 w-4" />