Files
frigate/web/src/components/input/TextEntry.tsx
T

94 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-04-03 12:34:19 -05:00
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/components/ui/form";
2025-03-17 13:50:13 -06:00
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;
2025-05-17 17:11:19 -05:00
regexPattern?: RegExp;
regexErrorMessage?: string;
2026-02-03 07:31:00 -07:00
forbiddenPattern?: RegExp;
forbiddenErrorMessage?: string;
2025-03-17 13:50:13 -06:00
};
2025-05-17 17:11:19 -05:00
2025-03-17 13:50:13 -06:00
export default function TextEntry({
2025-04-03 12:34:19 -05:00
defaultValue = "",
2025-03-17 13:50:13 -06:00
placeholder,
2025-04-03 12:34:19 -05:00
allowEmpty = false,
2025-03-17 13:50:13 -06:00
onSave,
children,
2025-05-17 17:11:19 -05:00
regexPattern,
regexErrorMessage = "Input does not match the required format",
2026-02-03 07:31:00 -07:00
forbiddenPattern,
forbiddenErrorMessage = "Input contains invalid characters",
2025-03-17 13:50:13 -06:00
}: TextEntryProps) {
const formSchema = z.object({
2025-05-17 17:11:19 -05:00
text: z
.string()
.optional()
2026-02-03 07:31:00 -07:00
.refine((val) => !val || !forbiddenPattern?.test(val), {
message: forbiddenErrorMessage,
})
2025-05-17 17:11:19 -05:00
.refine(
(val) => {
if (!allowEmpty && !val) return false;
if (val && regexPattern) return regexPattern.test(val);
return true;
},
{
message: regexPattern ? regexErrorMessage : "Field is required",
},
),
2025-03-17 13:50:13 -06:00
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: { text: defaultValue },
});
const onSubmit = useCallback(
(data: z.infer<typeof formSchema>) => {
2025-04-03 12:34:19 -05:00
onSave(data.text || "");
2025-03-17 13:50:13 -06:00
},
2025-04-03 12:34:19 -05:00
[onSave],
2025-03-17 13:50:13 -06:00
);
return (
<Form {...form}>
2025-04-03 12:34:19 -05:00
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
2025-03-17 13:50:13 -06:00
<FormField
control={form.control}
name="text"
2025-04-03 12:34:19 -05:00
render={({ field }) => (
2025-03-17 13:50:13 -06:00
<FormItem>
<FormControl>
<Input
2025-04-03 12:34:19 -05:00
{...field}
2026-05-29 17:00:30 -05:00
className="w-full"
2025-03-17 13:50:13 -06:00
placeholder={placeholder}
type="text"
/>
</FormControl>
2025-04-03 12:34:19 -05:00
<FormMessage className="text-xs text-destructive" />
2025-03-17 13:50:13 -06:00
</FormItem>
)}
/>
{children}
</form>
</Form>
);
}