gitscope
← marzneshin / v0.7.3 / dashboard/src/common/components/form-fields/clearable-text.tsx
https://dev.kronoz.win/r/marzneshin.git
dashboard/src/common/components/form-fields/clearable-text.tsx · TypeScript
Blame Raw
 1import {
 2    Button,
 3    FormControl,
 4    FormField,
 5    FormItem,
 6    FormLabel,
 7    FormMessage,
 8    Input,
 9} from "@marzneshin/common/components";
10import { useFormContext } from "react-hook-form";
11import { X } from "lucide-react";
12
13export const ClearableTextField = ({
14    name,
15    label,
16    placeholder = "",
17}: {
18    name: string;
19    label: string;
20    placeholder?: string;
21}) => {
22    const form = useFormContext();
23    const value = form.watch(name);
24
25    const handleNullify = () => {
26        form.setValue(name, null);
27    };
28
29    const handleRestore = () => {
30        form.setValue(name, "");
31    };
32
33    return (
34        <FormField
35            control={form.control}
36            name={name}
37            render={({ field }) => (
38                <FormItem className="w-full">
39                    <FormLabel>{label}</FormLabel>
40                    <FormControl>
41                        <div className="relative w-full flex items-center gap-2">
42                            {value === null ? (
43                                <div className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium">
44                                    null
45                                </div>
46                            ) : (
47                                <Input placeholder={placeholder} {...field} />
48                            )}
49                            <Button
50                                type="button"
51                                aria-label="clear"
52                                variant="ghost"
53                                size="icon"
54                                onClick={
55                                    value === null
56                                        ? handleRestore
57                                        : handleNullify
58                                }
59                                className="absolute hover:fg-destructive-background right-1 top-1/2 -translate-y-1/2 h-7"
60                            >
61                                <X className="h-4 w-4 " />
62                                <span className="sr-only">Clear</span>
63                            </Button>
64                        </div>
65                    </FormControl>
66                    <FormMessage />
67                </FormItem>
68            )}
69        />
70    );
71};