From 32ec2df3c8615b0b1bf932d1b4d417c705bcf0f7 Mon Sep 17 00:00:00 2001 From: Vanxh Date: Mon, 21 Aug 2023 01:45:06 +0530 Subject: [PATCH] Automatically generate slug based on title (#213) --- apps/web/src/components/forms/status-page-form.tsx | 11 +++++++++-- apps/web/src/lib/utils.ts | 9 ++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/forms/status-page-form.tsx b/apps/web/src/components/forms/status-page-form.tsx index 399c927a4..886244b93 100644 --- a/apps/web/src/components/forms/status-page-form.tsx +++ b/apps/web/src/components/forms/status-page-form.tsx @@ -26,6 +26,7 @@ import { import { Input } from "@/components/ui/input"; import { useToast } from "@/components/ui/use-toast"; import { useDebounce } from "@/hooks/use-debounce"; +import { slugify } from "@/lib/utils"; import { api } from "@/trpc/client"; import { LoadingAnimation } from "../loading-animation"; @@ -62,6 +63,7 @@ export function StatusPageForm({ const [isPending, startTransition] = useTransition(); const watchSlug = form.watch("slug"); const debouncedSlug = useDebounce(watchSlug, 1000); // using debounce to not exhaust the server + const watchTitle = form.watch("title"); const { toast } = useToast(); const checkUniqueSlug = useCallback(async () => { @@ -85,10 +87,15 @@ export function StatusPageForm({ form.clearErrors("slug"); } } - watchSlugChanges(); + + void watchSlugChanges(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [checkUniqueSlug]); + useEffect(() => { + form.setValue("slug", slugify(watchTitle)); + }, [watchTitle, form]); + const onSubmit = async ({ ...props }: z.infer) => { @@ -144,7 +151,7 @@ export function StatusPageForm({ }); } else { if (onSubmit) { - form.handleSubmit(onSubmit)(e); + void form.handleSubmit(onSubmit)(e); } } }} diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts index 88e20cf55..a1cc8a11c 100644 --- a/apps/web/src/lib/utils.ts +++ b/apps/web/src/lib/utils.ts @@ -1,5 +1,5 @@ -import { clsx } from "clsx"; import type { ClassValue } from "clsx"; +import { clsx } from "clsx"; import { format } from "date-fns"; import { twMerge } from "tailwind-merge"; @@ -20,3 +20,10 @@ export function notEmpty( ): value is TValue { return value !== null && value !== undefined; } + +export const slugify = (str: string) => { + return str + .toLowerCase() + .replace(/ /g, "-") + .replace(/[^\w-]+/g, ""); +}; -- 2.51.2