Added some error message handling and added basic info about functionality on ui

This commit is contained in:
Tom
2024-01-06 20:17:04 +00:00
parent 0f7fb11f4e
commit 68df045c54
13 changed files with 232 additions and 93 deletions

View File

@ -10,11 +10,16 @@ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, Command
import { Input } from "@/components/ui/input";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Label } from "@/components/ui/label";
import { ToastAction } from "@/components/ui/toast"
import { useToast } from "@/components/ui/use-toast"
import InfoNotice from "@/components/elements/info-notice";
import { Toaster } from "@/components/ui/toaster";
import { stringifyError } from "next/dist/shared/lib/utils";
const TTSFiltersPage = () => {
@ -23,6 +28,8 @@ const TTSFiltersPage = () => {
const [tag, setTag] = useState("blacklisted")
const [open, setOpen] = useState(false)
const [userTags, setUserTag] = useState<{ username: string, tag: string }[]>([])
const { toast } = useToast()
const [error, setError] = useState("")
const router = useRouter();
const tags = [
@ -30,9 +37,24 @@ const TTSFiltersPage = () => {
"priority"
]
const toasting = (title: string, error: Error) => {
toast({
title: title,
description: error.message,
variant: "error"
})
}
const success = (title: string, description: string) => {
toast({
title: title,
description: description,
variant: "success"
})
}
// Username blacklist
const usernameFilteredFormSchema = z.object({
//userId: z.string().trim().min(1),
username: z.string().trim().min(4).max(25).regex(new RegExp("[a-zA-Z0-9][a-zA-Z0-9\_]{3,24}"), "Must be a valid twitch username."),
tag: z.string().trim()
});
@ -40,7 +62,6 @@ const TTSFiltersPage = () => {
const usernameFilteredForm = useForm({
resolver: zodResolver(usernameFilteredFormSchema),
defaultValues: {
//userId: session?.user?.id ?? "",
username: "",
tag: ""
}
@ -52,18 +73,18 @@ const TTSFiltersPage = () => {
const userFiltersData = await axios.get("/api/settings/tts/filter/users")
setUserTag(userFiltersData.data ?? [])
} catch (error) {
console.log("ERROR", error)
toasting("Failed to fetch all the username filters.", error as Error)
}
try {
const replacementData = await axios.get("/api/settings/tts/filter/words")
setReplacements(replacementData.data ?? [])
} catch (e) {
console.log("ERROR", e)
} catch (error) {
toasting("Failed to fetch all the word filters.", error as Error)
}
};
fetchData().catch(console.error);
fetchData().catch((error) => toasting("Failed to fetch all the username filters.", error as Error));
}, []);
const onDelete = () => {
@ -71,33 +92,34 @@ const TTSFiltersPage = () => {
axios.delete("/api/settings/tts/filter/users?username=" + username)
.then(() => {
setUserTag(userTags.filter((u) => u.username != username))
}).catch((e) => console.error(e))
success("Username filter deleted", `"${username.toLowerCase()}" is now back to normal.`)
}).catch((error) => toasting("Failed to delete the username filter.", error as Error))
}
const isSubmitting = usernameFilteredForm.formState.isSubmitting;
const onAddExtended = (values: z.infer<typeof usernameFilteredFormSchema>, test: boolean = true) => {
try {
const original = userTags.find(u => u.username.toLowerCase() == values.username.toLowerCase())
const original = userTags.find(u => u.username.toLowerCase() == values.username.toLowerCase())
if (test)
values.tag = tag
axios.post("/api/settings/tts/filter/users", values)
.then((d) => {
if (original == null) {
userTags.push({ username: values.username.toLowerCase(), tag: values.tag })
} else {
original.tag = values.tag
}
setUserTag(userTags)
if (test)
values.tag = tag
axios.post("/api/settings/tts/filter/users", values)
.then((d) => {
if (original == null) {
userTags.push({ username: values.username.toLowerCase(), tag: values.tag })
} else {
original.tag = values.tag
}
setUserTag(userTags)
usernameFilteredForm.reset();
router.refresh();
})
} catch (error) {
console.log("[TTS/FILTERS/USER]", error);
}
usernameFilteredForm.reset();
router.refresh();
if (values.tag == "blacklisted")
success("Username filter added", `"${values.username.toLowerCase()}" will be blocked.`)
else if (values.tag == "priority")
success("Username filter added", `"${values.username.toLowerCase()}" will be taking priority.`)
}).catch(error => toasting("Failed to add the username filter.", error as Error))
}
const onAdd = (values: z.infer<typeof usernameFilteredFormSchema>) => {
@ -108,27 +130,24 @@ const TTSFiltersPage = () => {
const [replacements, setReplacements] = useState<{ id: string, search: string, replace: string, userId: string }[]>([])
const onReplaceAdd = async () => {
if (search.length <= 0) {
toasting("Unable to add the word filter.", new Error("Search must not be empty."))
return
}
await axios.post("/api/settings/tts/filter/words", { search, replace })
.then(d => {
replacements.push({ id: d.data.id, search: d.data.search, replace: d.data.replace, userId: d.data.userId })
setReplacements(replacements)
setSearch("")
}).catch(e => {
// TODO: handle already exist.
console.log("LOGGED:", e)
return null
})
success("Word filter added", `"${d.data.search}" will be replaced.`)
}).catch(error => toasting("Failed to add the word filter.", error as Error))
}
const onReplaceUpdate = async (data: { id: string, search: string, replace: string, userId: string }) => {
await axios.put("/api/settings/tts/filter/words", data)
.then(d => {
//setReplacements(replacements.filter(r => r.id != id))
}).catch(e => {
// TODO: handle does not exist.
console.log("LOGGED:", e)
return null
})
.then(() => success("Word filter updated", ""))
.catch(error => toasting("Failed to update the word filter.", error as Error))
}
const onReplaceDelete = async (id: string) => {
@ -136,29 +155,10 @@ const TTSFiltersPage = () => {
.then(d => {
const r = replacements.filter(r => r.id != d.data.id)
setReplacements(r)
console.log(r)
}).catch(e => {
// TODO: handle does not exist.
console.log("LOGGED:", e)
return null
})
success("Word filter deleted", `No more filter for "${d.data.search}"`)
}).catch(error => toasting("Failed to delete the word filter.", error as Error))
}
// const replaceFormSchema = z.object({
// //userId: z.string().trim().min(1),
// search: z.string().trim().min(1),
// replace: z.string().trim().min(0),
// });
// const replaceForm = useForm({
// resolver: zodResolver(replaceFormSchema),
// defaultValues: {
// //userId: session?.user?.id ?? "",
// search: "",
// replace: ""
// }
// });
let [search, setSearch] = useState("")
let [replace, setReplace] = useState("")
let [searchInfo, setSearchInfo] = useState("")
@ -166,10 +166,11 @@ const TTSFiltersPage = () => {
return (
<div>
<div className="text-2xl text-center pt-[50px]">TTS Filters</div>
<div className="px-10 py-5 w-full h-full flex-grow inset-y-1/2">
<div className="px-10 py-1 w-full h-full flex-grow inset-y-1/2">
<InfoNotice message="You can tag certain labels to twitch users, allowing changes applied specifically to these users when using the text to speech feature." hidden={false} />
<div>
{userTags.map((user, index) => (
<div key={user.username + "-tags"} className="flex w-full items-start justify-between rounded-md border px-4 py-1">
<div key={user.username + "-tags"} className="flex w-full items-start justify-between rounded-md border px-4 py-2 mt-2">
<p className="text-base font-medium">
<span className="mr-2 rounded-lg bg-primary px-2 py-1 text-xs text-primary-foreground">
{user.tag}
@ -228,7 +229,7 @@ const TTSFiltersPage = () => {
))}
<Form {...usernameFilteredForm}>
<form onSubmit={usernameFilteredForm.handleSubmit(onAdd)}>
<div className="flex w-full items-center justify-between rounded-md border px-4 py-2 gap-3">
<div className="flex w-full items-center justify-between rounded-md border px-4 py-2 gap-3 mt-2">
<Label className="rounded-lg bg-primary px-2 py-1 text-xs text-primary-foreground ">
{tag}
</Label>
@ -336,6 +337,7 @@ const TTSFiltersPage = () => {
</div>
</div>
</div>
<Toaster />
</div>
);
}

View File

@ -13,6 +13,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import voices from "@/data/tts";
import InfoNotice from "@/components/elements/info-notice";
const TTSVoiceFiltersPage = () => {
const { data: session, status } = useSession();
@ -94,8 +95,7 @@ const TTSVoiceFiltersPage = () => {
setValue(Number.parseInt(currentValue))
onDefaultChange(voice.label)
setOpen(false)
}}
>
}}>
<Check
className={cn(
"mr-2 h-4 w-4",
@ -113,6 +113,7 @@ const TTSVoiceFiltersPage = () => {
<div className="w-full pt-[50px]">
<p className="text-xl text-center justify-center">Voices Enabled</p>
<InfoNotice message="Voices can be disabled from being used. Default voice will always work." hidden={false} />
<div className="grid grid-cols-4 grid-flow-row gap-4 pt-[20px]">
{voices.map((v, i) => (
<div key={v.label + "-enabled"} className="h-[30px] row-span-1 col-span-1 align-middle flex items-center justify-center">