refactor: use react hook form

This commit is contained in:
Mauricio Siu
2024-12-24 14:47:42 -06:00
parent 0db98c0b92
commit ce19a42aee

View File

@@ -10,7 +10,6 @@ import {
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { import {
Select, Select,
SelectContent, SelectContent,
@@ -18,61 +17,56 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { api } from "@/utils/api"; import { api } from "@/utils/api";
import { ArrowRightLeft, Plus, Trash2 } from "lucide-react"; import { ArrowRightLeft, Plus, Trash2 } from "lucide-react";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import type React from "react"; import type React from "react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { toast } from "sonner"; import { toast } from "sonner";
import { z } from "zod";
import { useFieldArray, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
/**
* Props for the ManageTraefikPorts component
* @interface Props
* @property {React.ReactNode} children - The trigger element that opens the ports management modal
* @property {string} [serverId] - Optional ID of the server whose ports are being managed
*/
interface Props { interface Props {
children: React.ReactNode; children: React.ReactNode;
serverId?: string; serverId?: string;
} }
/** const PortSchema = z.object({
* Represents a port mapping configuration for Traefik targetPort: z.number().min(1, "Target port is required"),
* @interface AdditionalPort publishedPort: z.number().min(1, "Published port is required"),
* @property {number} targetPort - The internal port that the service is listening on publishMode: z.enum(["ingress", "host"]),
* @property {number} publishedPort - The external port that will be exposed });
* @property {"ingress" | "host"} publishMode - The Docker Swarm publish mode:
* - "host": Publishes the port directly on the host const TraefikPortsSchema = z.object({
* - "ingress": Publishes the port through the Swarm routing mesh ports: z.array(PortSchema),
*/ });
interface AdditionalPort {
targetPort: number; type TraefikPortsForm = z.infer<typeof TraefikPortsSchema>;
publishedPort: number;
publishMode: "ingress" | "host";
}
/**
* ManageTraefikPorts is a component that provides a modal interface for managing
* additional port mappings for Traefik in a Docker Swarm environment.
*
* Features:
* - Add, remove, and edit port mappings
* - Configure target port, published port, and publish mode for each mapping
* - Persist port configurations through API calls
*
* @component
* @example
* ```tsx
* <ManageTraefikPorts serverId="server-123">
* <Button>Manage Ports</Button>
* </ManageTraefikPorts>
* ```
*/
export const ManageTraefikPorts = ({ children, serverId }: Props) => { export const ManageTraefikPorts = ({ children, serverId }: Props) => {
const { t } = useTranslation("settings"); const { t } = useTranslation("settings");
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [additionalPorts, setAdditionalPorts] = useState<AdditionalPort[]>([]);
const [isDirty, setIsDirty] = useState(false); const form = useForm<TraefikPortsForm>({
resolver: zodResolver(TraefikPortsSchema),
defaultValues: {
ports: [],
},
});
const { fields, append, remove } = useFieldArray({
control: form.control,
name: "ports",
});
const { data: currentPorts, refetch: refetchPorts } = const { data: currentPorts, refetch: refetchPorts } =
api.settings.getTraefikPorts.useQuery({ api.settings.getTraefikPorts.useQuery({
@@ -88,38 +82,27 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => {
useEffect(() => { useEffect(() => {
if (currentPorts) { if (currentPorts) {
setAdditionalPorts(currentPorts); form.reset({ ports: currentPorts });
} }
}, [currentPorts]); }, [currentPorts, form]);
const handleAddPort = () => { const handleAddPort = () => {
setAdditionalPorts([ append({ targetPort: 0, publishedPort: 0, publishMode: "host" });
...additionalPorts,
{ targetPort: 0, publishedPort: 0, publishMode: "host" },
]);
setIsDirty(true);
}; };
const handleUpdatePorts = async () => { const onSubmit = async (data: TraefikPortsForm) => {
try { try {
await updatePorts({ await updatePorts({
serverId, serverId,
additionalPorts, additionalPorts: data.ports,
}); });
toast.success(t("settings.server.webServer.traefik.portsUpdated")); toast.success(t("settings.server.webServer.traefik.portsUpdated"));
setOpen(false); setOpen(false);
setIsDirty(false);
} catch (error) { } catch (error) {
toast.error(t("settings.server.webServer.traefik.portsUpdateError")); toast.error(t("settings.server.webServer.traefik.portsUpdateError"));
} }
}; };
const handleRemovePort = (index: number) => {
const newPorts = additionalPorts.filter((_, i) => i !== index);
setAdditionalPorts(newPorts);
setIsDirty(true);
};
return ( return (
<> <>
<div onClick={() => setOpen(true)}>{children}</div> <div onClick={() => setOpen(true)}>{children}</div>
@@ -144,8 +127,10 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => {
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<div className="grid gap-6 py-4"> <div className="grid gap-6 py-4">
{additionalPorts.length === 0 ? ( {fields.length === 0 ? (
<div className="flex w-full flex-col items-center justify-center gap-3 pt-10"> <div className="flex w-full flex-col items-center justify-center gap-3 pt-10">
<ArrowRightLeft className="size-8 text-muted-foreground" /> <ArrowRightLeft className="size-8 text-muted-foreground" />
<span className="text-base text-muted-foreground text-center"> <span className="text-base text-muted-foreground text-center">
@@ -157,94 +142,97 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => {
</div> </div>
) : ( ) : (
<div className="grid gap-4"> <div className="grid gap-4">
{additionalPorts.map((port, index) => ( {fields.map((field, index) => (
<Card key={index}> <Card key={field.id}>
<CardContent className="grid grid-cols-[1fr_1fr_1.5fr_auto] gap-4 p-4 transparent"> <CardContent className="grid grid-cols-[1fr_1fr_1.5fr_auto] gap-4 p-4 transparent">
<div className="space-y-2"> <FormField
<Label control={form.control}
htmlFor={`target-port-${index}`} name={`ports.${index}.targetPort`}
className="text-sm font-medium text-muted-foreground" render={({ field }) => (
> <FormItem>
{t("settings.server.webServer.traefik.targetPort")} <FormLabel className="text-sm font-medium text-muted-foreground">
</Label> {t(
"settings.server.webServer.traefik.targetPort",
)}
</FormLabel>
<FormControl>
<Input <Input
id={`target-port-${index}`}
type="number" type="number"
value={port.targetPort} {...field}
onChange={(e) => { onChange={(e) =>
const newPorts = [...additionalPorts]; field.onChange(Number(e.target.value))
if (newPorts[index]) {
newPorts[index].targetPort = Number.parseInt(
e.target.value,
);
} }
setAdditionalPorts(newPorts);
}}
className="w-full dark:bg-black" className="w-full dark:bg-black"
placeholder="e.g. 8080" placeholder="e.g. 8080"
/> />
</div> </FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="space-y-2"> <FormField
<Label control={form.control}
htmlFor={`published-port-${index}`} name={`ports.${index}.publishedPort`}
className="text-sm font-medium text-muted-foreground" render={({ field }) => (
> <FormItem>
{t("settings.server.webServer.traefik.publishedPort")} <FormLabel className="text-sm font-medium text-muted-foreground">
</Label> {t(
"settings.server.webServer.traefik.publishedPort",
)}
</FormLabel>
<FormControl>
<Input <Input
id={`published-port-${index}`} type="number"
type="text" {...field}
value={port.publishedPort} onChange={(e) =>
onChange={(e) => { field.onChange(Number(e.target.value))
const newPorts = [...additionalPorts];
if (newPorts[index]) {
newPorts[index].publishedPort = Number.parseInt(
e.target.value,
);
} }
setAdditionalPorts(newPorts);
}}
className="w-full dark:bg-black" className="w-full dark:bg-black"
placeholder="e.g. 80" placeholder="e.g. 80"
/> />
</div> </FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="space-y-2"> <FormField
<Label control={form.control}
htmlFor={`publish-mode-${index}`} name={`ports.${index}.publishMode`}
className="text-sm font-medium text-muted-foreground" render={({ field }) => (
> <FormItem>
{t("settings.server.webServer.traefik.publishMode")} <FormLabel className="text-sm font-medium text-muted-foreground">
</Label> {t(
"settings.server.webServer.traefik.publishMode",
)}
</FormLabel>
<Select <Select
value={port.publishMode} onValueChange={field.onChange}
onValueChange={(value: "ingress" | "host") => { value={field.value}
const newPorts = [...additionalPorts];
if (newPorts[index]) {
newPorts[index].publishMode = value;
}
setAdditionalPorts(newPorts);
}}
>
<SelectTrigger
id={`publish-mode-${index}`}
className="dark:bg-black"
> >
<FormControl>
<SelectTrigger className="dark:bg-black">
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
</FormControl>
<SelectContent> <SelectContent>
<SelectItem value="host">Host Mode</SelectItem> <SelectItem value="host">
Host Mode
</SelectItem>
<SelectItem value="ingress"> <SelectItem value="ingress">
Ingress Mode Ingress Mode
</SelectItem> </SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> <FormMessage />
</FormItem>
)}
/>
<div className="flex items-end"> <div className="flex items-end">
<Button <Button
onClick={() => handleRemovePort(index)} onClick={() => remove(index)}
variant="ghost" variant="ghost"
size="icon" size="icon"
className="text-muted-foreground hover:text-destructive" className="text-muted-foreground hover:text-destructive"
@@ -258,7 +246,7 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => {
</div> </div>
)} )}
{additionalPorts.length > 0 && ( {fields.length > 0 && (
<AlertBlock type="info"> <AlertBlock type="info">
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<span className="text-sm"> <span className="text-sm">
@@ -268,12 +256,12 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => {
</strong> </strong>
<ul className="pt-2"> <ul className="pt-2">
<li> <li>
<strong>Host Mode:</strong> Directly binds the port to <strong>Host Mode:</strong> Directly binds the port
the host machine. to the host machine.
<ul className="p-2 list-inside list-disc"> <ul className="p-2 list-inside list-disc">
<li> <li>
Best for single-node deployments or when you need Best for single-node deployments or when you
guaranteed port availability. need guaranteed port availability.
</li> </li>
</ul> </ul>
</li> </li>
@@ -282,8 +270,8 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => {
Swarm's load balancer. Swarm's load balancer.
<ul className="p-2 list-inside list-disc"> <ul className="p-2 list-inside list-disc">
<li> <li>
Recommended for multi-node deployments and better Recommended for multi-node deployments and
scalability. better scalability.
</li> </li>
</ul> </ul>
</li> </li>
@@ -294,18 +282,18 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => {
)} )}
</div> </div>
<DialogFooter className=""> <DialogFooter>
{(additionalPorts.length > 0 || isDirty) && (
<Button <Button
type="submit"
variant="default" variant="default"
className="text-sm" className="text-sm"
onClick={handleUpdatePorts} isLoading={isLoading}
disabled={isLoading || !isDirty}
> >
Save Save
</Button> </Button>
)}
</DialogFooter> </DialogFooter>
</form>
</Form>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</> </>