gitscope
← marzneshin / v0.3.0 / dashboard/src/features/services/dialogs/mutation/index.tsx
https://dev.kronoz.win/r/marzneshin.git
dashboard/src/features/services/dialogs/mutation/index.tsx · TypeScript
Blame Raw
 1import {
 2    DialogTitle,
 3    DialogContent,
 4    Dialog,
 5    DialogHeader,
 6    Form,
 7    Button,
 8} from "@marzneshin/components";
 9import type { FC } from "react";
10import {
11    type ServiceType,
12    useServicesCreationMutation,
13    useServicesUpdateMutation,
14} from "@marzneshin/features/services";
15import { useTranslation } from "react-i18next";
16import { z } from "zod";
17import { useMutationDialog } from "@marzneshin/hooks";
18import { NameField, InboundsField } from "./fields";
19
20export const ServiceSchema = z.object({
21    id: z.number().optional(),
22    inbounds: z.array(z.number()).refine((value) => value.some((item) => item), {
23        message: "You have to select at least one inbound.",
24    }),
25    name: z.string().trim().min(1),
26});
27type ServiceCreateType = z.infer<typeof ServiceSchema>;
28
29interface MutationDialogProps {
30    entity: ServiceType | null;
31    open: boolean;
32    onOpenChange: (state: boolean) => void;
33}
34
35const getDefaultValues = (): ServiceCreateType => ({
36    name: "",
37    inbounds: [],
38});
39
40export const MutationDialog: FC<MutationDialogProps> = ({
41    entity,
42    open,
43    onOpenChange,
44}) => {
45    const isEditing = entity !== null;
46    const updateMutation = useServicesUpdateMutation();
47    const createMutation = useServicesCreationMutation();
48    const { form, handleSubmit } = useMutationDialog({
49        entity,
50        updateMutation,
51        createMutation,
52        getDefaultValue: getDefaultValues,
53        schema: ServiceSchema,
54        onOpenChange,
55    });
56    const { t } = useTranslation();
57    return (
58        <Dialog open={open} onOpenChange={onOpenChange} defaultOpen={true}>
59            <DialogContent>
60                <DialogHeader>
61                    <DialogTitle className="text-primary">
62                        {isEditing
63                            ? t("page.services.dialogs.edition.title")
64                            : t("page.services.dialogs.creation.title")}
65                    </DialogTitle>
66                </DialogHeader>
67                <Form {...form}>
68                    <form onSubmit={handleSubmit} className="h-full">
69                        <NameField />
70                        <InboundsField />
71                        <Button
72                            className="mt-3 w-full font-semibold"
73                            type="submit"
74                            disabled={form.formState.isSubmitting}
75                        >
76                            {t("submit")}
77                        </Button>
78                    </form>
79                </Form>
80            </DialogContent>
81        </Dialog>
82    );
83};