import { Form, FormControl, FormField, FormItem, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { zodResolver } from "@hookform/resolvers/zod"; import React, { useCallback } from "react"; import { useForm } from "react-hook-form"; import { z } from "zod"; type TextEntryProps = { defaultValue?: string; placeholder?: string; allowEmpty?: boolean; onSave: (text: string) => void; children?: React.ReactNode; regexPattern?: RegExp; regexErrorMessage?: string; }; export default function TextEntry({ defaultValue = "", placeholder, allowEmpty = false, onSave, children, regexPattern, regexErrorMessage = "Input does not match the required format", }: TextEntryProps) { const formSchema = z.object({ text: z .string() .optional() .refine( (val) => { if (!allowEmpty && !val) return false; if (val && regexPattern) return regexPattern.test(val); return true; }, { message: regexPattern ? regexErrorMessage : "Field is required", }, ), }); const form = useForm>({ resolver: zodResolver(formSchema), defaultValues: { text: defaultValue }, }); const onSubmit = useCallback( (data: z.infer) => { onSave(data.text || ""); }, [onSave], ); return (
( )} /> {children} ); }