diff --git a/components/RouteDialog.tsx b/components/RouteDialog.tsx new file mode 100644 index 0000000..25e666e --- /dev/null +++ b/components/RouteDialog.tsx @@ -0,0 +1,125 @@ +import { updateRoute } from "@/lib/clientActions"; +import { getHosts, getRouteUpstreams } from "@/lib/utils"; +import { useState } from "react"; +import useSWRMutation from "swr/mutation"; +import { toast } from "./ui/use-toast"; +import { useFieldArray, useForm } from "react-hook-form"; +import { set } from "lodash"; +import { Dialog, DialogContent } from "./ui/dialog"; +import { Form, FormControl, FormField, FormItem, FormLabel } from "./ui/form"; +import { Input } from "./ui/input"; +import { Button } from "./ui/button"; + +export function RouteDialog({ route }: { route: Route }) { + let index = getHosts(route).indexOf(route.match[0].host[0]); + + const [modifiedRoute, setRoute] = useState(route); + const { trigger: pushUpdate } = useSWRMutation(`/api/caddy/routes/${index}`, updateRoute, { + onError: () => { + return toast({ + title: "Error", + description: "There was an error updating the route", + variant: "destructive" + }); + }, + onSuccess: () => { + toast({ + title: "Success", + description: "Route updated successfully!", + variant: "success" + }); + } + }); + + let validHosts: any[] = getHosts(route); + let validUpstreams: any[] = getRouteUpstreams(route).map((upstream) => upstream.dial); + + const form = useForm({ + values: { + handler: route.handle[0].routes[0].handle[0].handler, + upstreams: validUpstreams, + hosts: validHosts, + } + }); + + const { fields: upstreams, append: appendUpstreams } = useFieldArray({ + control: form.control, + name: "upstreams", + }) + + const { fields: hosts, append: appendHosts } = useFieldArray({ + control: form.control, + name: "hosts", + }) + + let onSubmit = (() => { + pushUpdate(modifiedRoute); + }) + + + let handleChange = (value: any, path: any) => { + let updatedRoute = set(modifiedRoute, path, value.target.value); + setRoute(updatedRoute); + form.setValue(value.target.name, value.target.value) + } + + + return ( + + +
+ + ( + + Handler + + handleChange(value, `handle[0].handler`)} /> + + + )} + + > + + {upstreams.map((upstream, index) => ( + ( + + Upstream {index + 1} + + handleChange(value, `handle[0].routes[0].handle[0].upstreams[${index}].dial`)} /> + + + )} + /> + ))} + + {hosts.map((host, index) => ( + ( + + Host {index + 1} + + handleChange(value, `match[0].host[${index}]`)} /> + + + )} + /> + ))} + + + + + +
+
+ ) +} \ No newline at end of file