feat: enter key to submit dialog

This commit is contained in:
trafficlunar 2025-01-29 20:31:13 +00:00
parent 9cd8c0f18d
commit 88b43829bc
8 changed files with 41 additions and 18 deletions

View file

@ -1,5 +1,5 @@
import { Dialog } from "@/components/ui/dialog";
import { createContext, lazy, ReactNode, Suspense, useState } from "react";
import { createContext, lazy, ReactNode, Suspense, useRef, useState } from "react";
type Context = (id: string) => void;
@ -13,19 +13,29 @@ export const DialogProvider = ({ children }: Props) => {
const [open, setOpen] = useState(false);
const [id, setId] = useState("");
const onSubmitRef = useRef<(() => void) | null>(null);
const openDialog = (id: string) => {
setId(id);
setOpen(true);
};
const LazyDialogContent = id ? lazy(() => import(`@/components/dialogs/${id}.tsx`)) : null;
const dialogKeyHandler = (e: React.KeyboardEvent) => {
if (!onSubmitRef.current) return;
if (e.key !== "Enter") return;
onSubmitRef.current();
close();
};
const LazyDialogContent = id ? lazy<React.ComponentType<DialogProps>>(() => import(`@/components/dialogs/${id}.tsx`)) : null;
return (
<DialogContext.Provider value={openDialog}>
<Dialog open={open} onOpenChange={(value) => setOpen(value)}>
{LazyDialogContent && (
<Suspense fallback={<div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">Loading dialog...</div>}>
<LazyDialogContent close={() => setOpen(false)} />
<LazyDialogContent close={() => setOpen(false)} registerSubmit={(fn) => (onSubmitRef.current = fn)} dialogKeyHandler={dialogKeyHandler} />
</Suspense>
)}
</Dialog>