Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add regexes visualization, editing and deletion to service page #38

Merged
merged 5 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 188 additions & 0 deletions web/frontend/src/components/ServiceRegexesList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import { Button, Input, Spinner, Tab, Tabs, Tooltip } from "@nextui-org/react"
import { useEffect, useState } from "react"
import { FaArrowLeft, FaArrowRight, FaTrash } from "react-icons/fa6"
import { useFetch } from "../hooks/useFetch"
import { CerberoRegexes } from "../types/cerbero"
import { hexEncode } from "../utils/regexes"

export type ServiceRegexesListProps = {
nfq: string
}

export default function ServiceRegexesList({ nfq }: ServiceRegexesListProps) {
const [
regexesResponse,
regexesFetch,
isRegexesLoading,
regexesError
] = useFetch<CerberoRegexes>()

const [newRegex, setNewRegex] = useState("")

const [
,
newRegexFetch,
isNewRegexLoading,
] = useFetch()

const [
,
editRegexFetch,
isEditRegexFetchLoading
] = useFetch()

const [
,
deleteRegexFetch,
isDeleteRegexLoading,
] = useFetch()

useEffect(() => {
void regexesFetch(`/api/regexes/${nfq}`)
}, [])

async function addNewRegex() {
if(!newRegex) {
return
}

await newRegexFetch(`/api/regexes/${nfq}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
regexes: [newRegex]
})
})

setNewRegex("")
void regexesFetch(`/api/regexes/${nfq}`)
}

async function editRegex(regex: string, currentState: "active" | "inactive", newRegex: string, newState: "active" | "inactive") {
const reghex = hexEncode(regex)

await editRegexFetch(`/api/regexes/${nfq}?reghex=${reghex}&state=${currentState}`, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
regex: newRegex,
state: newState
})
})

void regexesFetch(`/api/regexes/${nfq}`)
}

async function deleteRegex(regex: string, state: "active" | "inactive") {
const reghex = hexEncode(regex)

await deleteRegexFetch(`/api/regexes/${nfq}?reghex=${reghex}&state=${state}`, {
method: "DELETE"
})

void regexesFetch(`/api/regexes/${nfq}`)
}

if(isRegexesLoading) {
return (
<div className="h-full w-full flex flex-col items-center justify-center">
<Spinner/>
</div>
)
}

if(regexesError) {
return (
<div className="h-full w-full flex flex-col items-center justify-center">
<span className="font-black text-xl text-zinc-300">{regexesError.status} ({regexesError.statusText})</span>
<span className="font-semibold text-zinc-600">{regexesError.data.error}</span>
</div>
)
}

return (
<Tabs aria-label="Options">
<Tab key="active" title="Active" className="h-full flex flex-col gap-2">
<div className="flex items-center gap-2 p-2 rounded-lg bg-default-200">
<Input
placeholder="New regex"
type="text"
variant="flat"
value={newRegex}
onChange={({ target }) => setNewRegex(target.value)}
className="bg-transparent"
/>
<Button isLoading={isNewRegexLoading} variant="flat" color="success" onPress={() => void addNewRegex()}>
<span className="font-bold">Add regex</span>
</Button>
</div>
{regexesResponse?.regexes.active.length === 0 ?
<div className="h-full w-full flex flex-col items-center justify-center">
<span className="font-bold text-zinc-600">No regexes here, add one from the input field above!</span>
</div> :
<ul className="h-full w-full flex flex-col gap-1">
{regexesResponse?.regexes.active.map((regex, i) => {
return (
<li key={i} className="text-sm bg-default-200 px-4 py-2 rounded-lg hover:opacity-75">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<span className="h-2 w-2 rounded-full bg-success"></span>
<span className="font-mono overflow-hidden line-clamp-1">{regex}</span>
</div>
<div className="flex items-center gap-1">
<Tooltip content="Deactivate regex" delay={1000} size="sm">
<Button isLoading={isEditRegexFetchLoading} onPress={() => void editRegex(regex, "active", regex, "inactive")} isIconOnly={true} color="danger" variant="flat" size="sm">
<FaArrowRight/>
</Button>
</Tooltip>
<Tooltip content="Delete regex" delay={1000} size="sm">
<Button isLoading={isDeleteRegexLoading} onPress={() => void deleteRegex(regex, "active")} isIconOnly={true} color="danger" variant="flat" size="sm">
<FaTrash/>
</Button>
</Tooltip>
</div>
</div>
</li>
)
})}
</ul>}
</Tab>
<Tab key="inactive" title="Inactive" className="flex flex-col h-full">
{regexesResponse?.regexes.inactive.length === 0 ?
<div className="h-full w-full flex flex-col items-center justify-center">
<span className="font-bold text-zinc-600">No regexes here, deactivate one from the `Active` tab.</span>
</div> :
<ul className="h-full w-full flex flex-col gap-1">
{regexesResponse?.regexes.inactive.map((regex, i) => {
return (
<li key={i} className="text-sm bg-default-200 px-4 py-2 rounded-lg hover:opacity-75">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<span className="h-2 w-2 rounded-full bg-success"></span>
<span className="font-mono">{regex}</span>
</div>
<div className="flex items-center gap-1">
<Tooltip content="Activate regex" delay={1000} size="sm">
<Button isLoading={isEditRegexFetchLoading} onPress={() => void editRegex(regex, "inactive", regex, "active")} isIconOnly={true} color="success" variant="flat" size="sm">
<FaArrowLeft/>
</Button>
</Tooltip>
<Tooltip content="Delete regex" delay={1000} size="sm">
<Button onPress={() => void deleteRegex(regex, "inactive")} isIconOnly={true} color="danger" variant="flat" size="sm">
<FaTrash/>
</Button>
</Tooltip>
</div>
</div>
</li>
)
})}
</ul>}
</Tab>
</Tabs>
)
}
45 changes: 26 additions & 19 deletions web/frontend/src/hooks/useFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,41 @@ export type UseFetchError = {
* 2. A `boolean` flag that states if the request is loading.
* 3. In case of an error a `UseFetchError` object, otherwise `undefined`.
*/
export function useFetch<T>(url: string, init?: RequestInit): [
export function useFetch<T>(): [
T | undefined,
() => Promise<void>,
(url: string, init?: RequestInit) => Promise<void>,
boolean,
UseFetchError | undefined
] {
] {
const [response, setResponse] = useState<T>()
const [isLoading, setIsLoading] = useState(false)
// TODO: set 400+ responses in response instead of error
const [error, setError] = useState<UseFetchError>()

async function triggerFetch() {
setIsLoading(true)
async function triggerFetch(url: string, init?: RequestInit) {
try {
setIsLoading(true)

const response = await fetch(url, init)
const responseJson = await response.json() as T
const response = await fetch(url, init)
const responseJson = await response.json() as T

if(response.ok) {
setResponse(responseJson)
if(response.ok) {
setResponse(responseJson)
}
else {
setError({
status: response.status,
statusText: response.statusText,
data: responseJson as UseFetchError["data"]
})
}
}
else {
setError({
status: response.status,
statusText: response.statusText,
data: responseJson as UseFetchError["data"]
})
catch(e) {
console.error(e)
}
finally {
setIsLoading(false)
}

setIsLoading(false)
}

return [
Expand Down Expand Up @@ -76,10 +83,10 @@ export function useFetchSync<T>(url: string, init?: RequestInit): [
triggerFetch,
isLoading,
error
] = useFetch<T>(url, init)
] = useFetch<T>()

useEffect(() => {
void triggerFetch()
void triggerFetch(url, init)
}, [])

return [
Expand Down
11 changes: 7 additions & 4 deletions web/frontend/src/pages/Service.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Chip } from "@nextui-org/react"
import { Card, CardBody, Chip } from "@nextui-org/react"
import { useParams } from "react-router-dom"
import Header from "../components/Header"
import ServiceRegexesList from "../components/ServiceRegexesList"
import { useFetchSync } from "../hooks/useFetch"
import Main from "../layouts/Main"
import Page from "../layouts/Page"
Expand Down Expand Up @@ -55,9 +56,11 @@ export default function Service() {
</div>
<div className="flex-1 flex flex-col gap-4 p-4">
<span className="font-bold text-3xl text-zinc-300">Regexes</span>
<div className="h-full w-full flex flex-col items-center justify-center bg-default-100 rounded-xl">
<span className="font-thin text-xl italic">Placeholder</span>
</div>
<Card className="h-full bg-default-100">
<CardBody>
<ServiceRegexesList nfq={nfq}/>
</CardBody>
</Card>
</div>
</div>
</div>
Expand Down
7 changes: 7 additions & 0 deletions web/frontend/src/utils/regexes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function hexEncode(s: string) {
const encoder = new TextEncoder()
const encodedArray = encoder.encode(s)
const encodedS = Array.from(encodedArray).map(byte => byte.toString(16).padStart(2, "0")).join("")

return encodedS
}
Loading