Started implementing editing of routes

This commit is contained in:
brian 2023-11-18 02:23:53 -05:00
parent 88556634f2
commit 38a66ae2b5
10 changed files with 464 additions and 42 deletions

View file

@ -36,8 +36,8 @@ export default function Home() {
</Card>
</div>
<div className='grid grid-flow-row-dense md:grid-cols-6 sm:grid-cols-2 p-2'>
<RouteCards routes={routes as Route[]} />
<RouteCards routes={routesMap} />
</div>
</main>
)
}
}

0
components/EditRoute.tsx Normal file
View file

View file

@ -1,6 +1,6 @@
import { cn } from "@/lib/utils"
import { NavigationMenuLink } from "@radix-ui/react-navigation-menu"
import React from "react"
import { NavigationMenu, NavigationMenuLink } from "./ui/navigation-menu"
const ListItem = React.forwardRef<
React.ElementRef<"a">,

View file

@ -4,13 +4,20 @@ import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "./ui/card";
import { getHosts, getRouteUpstreams } from '@/lib/utils';
import { toast } from './ui/use-toast';
import React from 'react';
import React, { useState } from 'react';
import useSWRMutation from 'swr/mutation';
import { deleteRoute } from '@/lib/clientActions';
import { Dialog, DialogContent, DialogHeader } from './ui/dialog';
import { DialogDescription, DialogTitle } from '@radix-ui/react-dialog';
import { Form, FormControl, FormField, FormItem, FormLabel } from './ui/form';
import { useForm } from 'react-hook-form';
import { Input } from './ui/input';
export default function RouteCards({ routes }: { routes: Route[] }) {
const { trigger } = useSWRMutation("/api/caddy/routes", deleteRoute, {
const [route, setRoute] = useState<Route>();
const { trigger: handleDelete } = useSWRMutation("/api/caddy/routes", deleteRoute, {
onError: () => {
return toast({
title: "Error",
@ -27,30 +34,102 @@ export default function RouteCards({ routes }: { routes: Route[] }) {
}
});
let editRoute = (route: Route) => {
setRoute(route);
}
return (
routes.map((route, index) => (
<div key={index} className='p-2'>
<Card key={index} className='w-[300px]'>
<CardHeader>
<CardTitle>{getHosts(route).values().next().value}</CardTitle>
{getHosts(route).map((route => <CardDescription key={route}>{route}</ CardDescription>))}
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm font-medium leading-none">
Tunneling to
</p>
<p className="text-sm text-muted-foreground">{getRouteUpstreams(route)?.map((upstream => upstream.dial))}</p>
</CardContent>
<CardFooter className="flex justify-between">
<Button onClick={() => { trigger(route) }}>Edit</Button>
<Button variant="destructive" onClick={() => { trigger(route) }}>Delete</Button>
</CardFooter>
</Card>
</div>
))
<>
<EditRouteDialog route={route} />
{
routes.map((route, index) => (
<div key={index} className='p-2'>
<Card key={index} className='w-[300px]'>
<CardHeader>
<CardTitle>{getHosts(route).values().next().value}</CardTitle>
{getHosts(route).map((route => <CardDescription key={route}>{route}</ CardDescription>))}
<CardDescription></CardDescription>
</CardHeader>
<CardContent>
<p className="text-sm font-medium leading-none">
Tunneling to
</p>
<p className="text-sm text-muted-foreground">{getRouteUpstreams(route)?.map((upstream => upstream.dial))}</p>
</CardContent>
<CardFooter className="flex justify-between">
<Button onClick={() => { editRoute(route) }}>Edit</Button>
<Button variant="destructive" onClick={() => { handleDelete(route) }}>Delete</Button>
</CardFooter>
</Card>
</div>
))}
</>
)
}
export function EditRouteDialog({ route }: { route?: Route }) {
const form = useForm();
let onSubmit = ((data: any) => {
console.log(JSON.stringify(data))
})
let targetRoute: Route = route as Route;
return (
<Dialog open={targetRoute != null}>
<DialogContent className='sm:max-w-[425px]'>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<FormField
control={form.control}
name="Handler"
render={({ field }) => (
<FormItem>
<FormLabel>Handler</FormLabel>
<FormControl>
<Input {...field} defaultValue={route?.handle[0].handler} />
</FormControl>
</FormItem>
)}
></FormField>
{route ? getRouteUpstreams(targetRoute)?.map((upstream, index) => (
<FormField
key={index}
control={form.control}
name="upstreams"
render={({ field }) => (
<FormItem>
<FormLabel>Upstream {index + 1}</FormLabel>
<FormControl>
<Input {...field} defaultValue={upstream.dial} />
</FormControl>
</FormItem>
)}
>
</FormField>
)) : <></>}
{route ? getHosts(targetRoute)?.map((host, index) => (
<FormField
key={index}
control={form.control}
name="upstreams"
render={({ field }) => (
<FormItem>
<FormLabel>Upstream {index + 1}</FormLabel>
<FormControl>
<Input {...field} defaultValue={host} />
</FormControl>
</FormItem>
)}
>
</FormField>
)) : <></>}
<Button type="submit">Save</Button>
</form>
</Form>
</DialogContent>
</Dialog >
)
}

122
components/ui/dialog.tsx Normal file
View file

@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { Cross2Icon } from "@radix-ui/react-icons"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<Cross2Icon className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}

176
components/ui/form.tsx Normal file
View file

@ -0,0 +1,176 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
ControllerProps,
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-[0.8rem] text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message) : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-[0.8rem] font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

25
components/ui/input.tsx Normal file
View file

@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

26
components/ui/label.tsx Normal file
View file

@ -0,0 +1,26 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View file

@ -1,9 +1,7 @@
import useSWR from "swr";
export async function useConfig() {
const { data, error, isLoading } = useSWR('/api/caddy/servers', fetcher, {
refreshInterval: 1000,
});
const { data, error, isLoading } = useSWR('/api/caddy/servers', fetcher);
return {
data,
error,
@ -12,10 +10,7 @@ export async function useConfig() {
}
export async function useServer() {
const { data, error, isLoading } = useSWR('/api/caddy/servers', fetcher, {
refreshInterval: 1000,
});
const { data, error, isLoading } = useSWR('/api/caddy/servers', fetcher);
return {
data,
error,
@ -24,10 +19,7 @@ export async function useConfig() {
}
export async function useUpstreamRoutes(route: Route) {
const { data, error, isLoading } = useSWR('http://192.168.1.69:2019/reverse_proxy/upstreams', fetcher, {
refreshInterval: 1000,
});
const { data, error, isLoading } = useSWR('http://192.168.1.69:2019/reverse_proxy/upstreams', fetcher);
return {
data,
error,
@ -37,10 +29,7 @@ export async function useConfig() {
}
export function useRoutes() {
const { data, error, isLoading } = useSWR('/api/caddy/routes', fetcher, {
refreshInterval: 1000,
});
const { data, error, isLoading } = useSWR('/api/caddy/routes', fetcher);
return {
data,
error,

View file

@ -9,9 +9,12 @@
"lint": "next lint"
},
"dependencies": {
"@hookform/resolvers": "^3.3.2",
"@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-avatar": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-navigation-menu": "^1.1.4",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.5",
@ -21,9 +24,11 @@
"next-themes": "^0.2.1",
"react": "^18",
"react-dom": "^18",
"react-hook-form": "^7.48.2",
"swr": "^2.2.4",
"tailwind-merge": "^2.0.0",
"tailwindcss-animate": "^1.0.7"
"tailwindcss-animate": "^1.0.7",
"zod": "^3.22.4"
},
"devDependencies": {
"@types/node": "^20",