feat:static page api, static/{slug} routing landing

This commit is contained in:
Rama Priyanto 2024-11-22 17:59:58 +07:00
parent b6e5e65144
commit 5e019e10b1
11 changed files with 832 additions and 37 deletions

View File

@ -3,7 +3,7 @@ import { Card } from "@nextui-org/react";
export default function StaticPageGenerator() {
return (
<Card className="rounded-md border bg-transparent p-4">
<Card className="rounded-md border bg-transparent p-4 overflow-auto">
<StaticPageBuilder />
</Card>
);

View File

@ -0,0 +1,10 @@
import StaticPageBuilderEdit from "@/components/form/static-page/static-page-edit-form";
import { Card } from "@nextui-org/react";
export default function StaticPageEdit() {
return (
<Card className="rounded-md border bg-transparent p-4 overflow-auto">
<StaticPageBuilderEdit />
</Card>
);
}

View File

@ -0,0 +1,38 @@
"use client";
import { HumasLayout } from "@/components/layout/humas-layout";
import { getCustomStaticDetailBySlug } from "@/service/static-page-service";
import { Card } from "@nextui-org/react";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
export default function StaticPage() {
const params = useParams();
const slug = params.slug;
const [htmlBody, setHtmlBody] = useState("");
useEffect(() => {
initFetch();
}, [slug]);
const initFetch = async () => {
const res = await getCustomStaticDetailBySlug(slug ? String(slug) : "");
const data = res?.data?.data;
setHtmlBody(data?.htmlBody);
};
const [hasMounted, setHasMounted] = useState(false);
useEffect(() => {
setHasMounted(true);
}, []);
if (!hasMounted) return null;
return (
<HumasLayout>
<Card className="rounded-md p-2 md:p-16">
<div dangerouslySetInnerHTML={{ __html: htmlBody }} />
</Card>
</HumasLayout>
);
}

View File

@ -153,7 +153,7 @@ export default function GenerateArticleForm() {
title: title,
typeId: parseInt(String(Array.from(article)[0])),
slug: slug,
categoryId: 12,
categoryId: 215,
tags: tags.join(","),
description: content,
htmlDescription: content,

View File

@ -63,10 +63,10 @@ const singleArticleSchema = z.object({
message: "Main Keyword must be at least 2 characters.",
}),
title: z.string().min(2, {
message: "Main Keyword must be at least 2 characters.",
message: "Title Keyword must be at least 2 characters.",
}),
additionalKeyword: z.string().min(2, {
message: "Main Keyword must be at least 2 characters.",
message: "Additional Keyword must be at least 2 characters.",
}),
});

View File

@ -146,6 +146,8 @@ export default function FormArticle() {
title: title,
typeId: parseInt(String(Array.from(article)[0])),
slug: slug,
categoryId: 215,
oldId: 1,
tags: tags.join(","),
description: content,
htmlDescription: content,

View File

@ -0,0 +1,223 @@
"use client";
import { Input, Textarea } from "@nextui-org/input";
import { Button, Card } from "@nextui-org/react";
import { useCallback, useEffect, useState } from "react";
import DOMPurify from "dompurify";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
createCustomStaticPage,
editCustomStaticPage,
getCustomStaticDetail,
} from "@/service/static-page-service";
import { close, error, loading } from "@/config/swal";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
const formSchema = z.object({
slug: z.string().min(2, {
message: "Slug must be at least 2 characters.",
}),
title: z.string().min(2, {
message: "Title must be at least 2 characters.",
}),
description: z.string().min(2, {
message: "Main Keyword must be at least 2 characters.",
}),
htmlBody: z.string().min(2, {
message: "Main Keyword must be at least 2 characters.",
}),
});
export default function StaticPageBuilderEdit() {
const MySwal = withReactContent(Swal);
const router = useRouter();
const params = useParams();
const id = params.id;
const formOptions = {
resolver: zodResolver(formSchema),
};
type UserSettingSchema = z.infer<typeof formSchema>;
const {
control,
handleSubmit,
formState: { errors },
watch,
setValue,
getValues,
} = useForm<UserSettingSchema>(formOptions);
useEffect(() => {
initFetch();
}, [id]);
const initFetch = async () => {
const res = await getCustomStaticDetail(id ? String(id) : "");
const data = res?.data?.data;
console.log("res", data);
setValue("title", data?.title);
setValue("slug", data?.slug);
setValue("description", data?.description);
setValue("htmlBody", data?.htmlBody);
};
const content = watch("htmlBody");
const generatedPage = useCallback(() => {
const sanitizedContent = DOMPurify.sanitize(getValues("htmlBody"));
return (
<Card className="rounded-md border p-4">
<div dangerouslySetInnerHTML={{ __html: sanitizedContent }} />
</Card>
);
}, [content]);
function createSlug(value: string): string {
return value
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-");
}
const onSubmit = async (values: z.infer<typeof formSchema>) => {
const request = {
id: Number(id),
title: values.title,
slug: values.slug,
description: values.description,
htmlBody: values.htmlBody,
};
loading();
const res = await editCustomStaticPage(request);
if (res?.error) {
error(res.message);
return false;
}
close();
successSubmit("/admin/static-page");
};
function successSubmit(redirect: any) {
MySwal.fire({
title: "Sukses",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then((result) => {
if (result.isConfirmed) {
router.push(redirect);
}
});
}
const title = watch("title");
useEffect(() => {
if (getValues("title")) {
setValue("slug", createSlug(getValues("title")));
}
}, [title]);
return (
<form
className="flex flex-col gap-3 px-4"
onSubmit={handleSubmit(onSubmit)}
>
<Controller
control={control}
name="title"
render={({ field: { onChange, value } }) => (
<Input
type="text"
id="title"
placeholder="Title"
label="Title"
value={value}
onChange={onChange}
labelPlacement="outside"
className="w-full"
variant="bordered"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title?.message}</p>
)}
<Controller
control={control}
name="slug"
render={({ field: { onChange, value } }) => (
<Input
type="text"
id="slug"
placeholder="Slug"
label="Slug"
value={value}
onChange={onChange}
labelPlacement="outside"
readOnly
className="w-full"
variant="bordered"
/>
)}
/>
<Controller
control={control}
name="description"
render={({ field: { onChange, value } }) => (
<Textarea
variant="bordered"
label="Description"
labelPlacement="outside"
placeholder="Description"
value={value}
onChange={onChange}
disableAutosize={false}
/>
)}
/>
{errors.description?.message && (
<p className="text-red-400 text-sm">{errors.description?.message}</p>
)}
<div className="grid grid-cols-1 md:grid-cols-2">
<div className="flex flex-col gap-2">
Editor
<Controller
control={control}
name="htmlBody"
render={({ field: { onChange, value } }) => (
<Textarea
variant="bordered"
label=""
labelPlacement="outside"
placeholder=""
className="max-h-[80vh]"
classNames={{
mainWrapper: "h-[80vh] overflow-hidden",
innerWrapper: "h-[80vh] overflow-hidden",
input: "min-h-full",
inputWrapper: "h-full",
}}
value={value}
onChange={onChange}
disableAutosize={false}
/>
)}
/>
</div>
<div className="px-4 flex flex-col gap-2">
Preview
{generatedPage()}
</div>
</div>
<div className="flex justify-end w-full">
<Button type="submit" color="primary" className="w-fit">
Save
</Button>
</div>
</form>
);
}

View File

@ -1,15 +1,53 @@
"use client";
import { Textarea } from "@nextui-org/input";
import { Card } from "@nextui-org/react";
import { useCallback, useState } from "react";
import { Input, Textarea } from "@nextui-org/input";
import { Button, Card } from "@nextui-org/react";
import { useCallback, useEffect, useState } from "react";
import DOMPurify from "dompurify";
import Script from "next/script";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { createCustomStaticPage } from "@/service/static-page-service";
import { close, error, loading } from "@/config/swal";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useRouter } from "next/navigation";
const formSchema = z.object({
slug: z.string().min(2, {
message: "Slug must be at least 2 characters.",
}),
title: z.string().min(2, {
message: "Title must be at least 2 characters.",
}),
description: z.string().min(2, {
message: "Main Keyword must be at least 2 characters.",
}),
htmlBody: z.string().min(2, {
message: "Main Keyword must be at least 2 characters.",
}),
});
export default function StaticPageBuilder() {
const [content, setContent] = useState("");
const MySwal = withReactContent(Swal);
const router = useRouter();
const formOptions = {
resolver: zodResolver(formSchema),
};
type UserSettingSchema = z.infer<typeof formSchema>;
const {
register,
control,
handleSubmit,
formState: { errors },
watch,
setValue,
getValues,
} = useForm<UserSettingSchema>(formOptions);
const content = watch("htmlBody");
const generatedPage = useCallback(() => {
const sanitizedContent = DOMPurify.sanitize(content);
const sanitizedContent = DOMPurify.sanitize(getValues("htmlBody"));
return (
<Card className="rounded-md border p-4">
<div dangerouslySetInnerHTML={{ __html: sanitizedContent }} />
@ -17,31 +55,150 @@ export default function StaticPageBuilder() {
);
}, [content]);
function createSlug(value: string): string {
return value
.toLowerCase()
.trim()
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-");
}
const onSubmit = async (values: z.infer<typeof formSchema>) => {
const request = {
title: values.title,
slug: values.slug,
description: values.description,
htmlBody: values.htmlBody,
};
loading();
const res = await createCustomStaticPage(request);
if (res?.error) {
error(res.message);
return false;
}
close();
successSubmit("/admin/static-page");
};
function successSubmit(redirect: any) {
MySwal.fire({
title: "Sukses",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then((result) => {
if (result.isConfirmed) {
router.push(redirect);
}
});
}
const title = watch("title");
useEffect(() => {
if (getValues("title")) {
setValue("slug", createSlug(getValues("title")));
}
}, [title]);
return (
<div className="grid grid-cols-1 md:grid-cols-2">
<div className="flex flex-col gap-2 px-4">
Editor
<Textarea
variant="bordered"
label=""
labelPlacement="outside"
placeholder=""
className="max-h-[80vh]"
classNames={{
mainWrapper: "h-[80vh] overflow-hidden",
innerWrapper: "h-[80vh] overflow-hidden",
input: "min-h-full",
inputWrapper: "h-full",
}}
value={content}
onValueChange={setContent}
disableAutosize={false}
/>
<form
className="flex flex-col gap-3 px-4"
onSubmit={handleSubmit(onSubmit)}
>
<Controller
control={control}
name="title"
render={({ field: { onChange, value } }) => (
<Input
type="text"
id="title"
placeholder="Title"
label="Title"
value={value}
onChange={onChange}
labelPlacement="outside"
className="w-full"
variant="bordered"
/>
)}
/>
{errors.title?.message && (
<p className="text-red-400 text-sm">{errors.title?.message}</p>
)}
<Controller
control={control}
name="slug"
render={({ field: { onChange, value } }) => (
<Input
type="text"
id="slug"
placeholder="Slug"
label="Slug"
value={value}
onChange={onChange}
labelPlacement="outside"
readOnly
className="w-full"
variant="bordered"
/>
)}
/>
<Controller
control={control}
name="description"
render={({ field: { onChange, value } }) => (
<Textarea
variant="bordered"
label="Description"
labelPlacement="outside"
placeholder="Description"
value={value}
onChange={onChange}
disableAutosize={false}
/>
)}
/>
{errors.description?.message && (
<p className="text-red-400 text-sm">{errors.description?.message}</p>
)}
<div className="grid grid-cols-1 md:grid-cols-2">
<div className="flex flex-col gap-2">
Editor
<Controller
control={control}
name="htmlBody"
render={({ field: { onChange, value } }) => (
<Textarea
variant="bordered"
label=""
labelPlacement="outside"
placeholder=""
className="max-h-[80vh]"
classNames={{
mainWrapper: "h-[80vh] overflow-hidden",
innerWrapper: "h-[80vh] overflow-hidden",
input: "min-h-full",
inputWrapper: "h-full",
}}
value={value}
onChange={onChange}
disableAutosize={false}
/>
)}
/>
</div>
<div className="px-4 flex flex-col gap-2">
Preview
{generatedPage()}
</div>
</div>
<div className="px-4 flex flex-col gap-2">
Preview
{generatedPage()}
<div className="flex justify-end w-full">
<Button type="submit" color="primary" className="w-fit">
Save
</Button>
</div>
</div>
</form>
);
}

View File

@ -1,9 +1,324 @@
"use client";
import { AddIcon } from "@/components/icons";
import ArticleTable from "@/components/table/article-table";
import { Button, Card } from "@nextui-org/react";
import {
CreateIconIon,
DeleteIcon,
DotsYIcon,
EyeIconMdi,
SearchIcon,
} from "@/components/icons";
import { error, success } from "@/config/swal";
import { deleteArticle, getListArticle } from "@/service/article";
import { getCustomStaticPage } from "@/service/static-page-service";
import { Article } from "@/types/globals";
import { convertDateFormat } from "@/utils/global";
import { Button } from "@nextui-org/button";
import {
Chip,
ChipProps,
Dropdown,
DropdownItem,
DropdownMenu,
DropdownTrigger,
Input,
Pagination,
Select,
SelectItem,
Spinner,
Table,
TableBody,
TableCell,
TableColumn,
TableHeader,
TableRow,
} from "@nextui-org/react";
import Link from "next/link";
import { Key, useCallback, useEffect, useState } from "react";
import Datepicker from "react-tailwindcss-datepicker";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
const columns = [
{ name: "No", uid: "no" },
{ name: "Judul", uid: "title" },
{ name: "Slug", uid: "slug" },
{ name: "Deskripsi", uid: "description" },
{ name: "Aksi", uid: "actions" },
];
type ArticleData = Article & {
no: number;
createdAt: string;
};
export default function StaticPageTable() {
return <ArticleTable />;
const MySwal = withReactContent(Swal);
const [page, setPage] = useState(1);
const [totalPage, setTotalPage] = useState(1);
const [article, setArticle] = useState<ArticleData[]>([]);
const [showData, setShowData] = useState("10");
const [search, setSearch] = useState("");
const [startDateValue, setStartDateValue] = useState({
startDate: null,
endDate: null,
});
useEffect(() => {
initState();
}, [page, showData, startDateValue]);
async function initState() {
const req = {
limit: showData,
page: page - 1,
search: search,
};
const res = await getCustomStaticPage(req);
getTableNumber(parseInt(showData), res.data?.data);
console.log("res.data?.data", res.data);
setTotalPage(res?.data?.meta?.totalPage);
}
const getTableNumber = (limit: number, data: Article[]) => {
if (data) {
const startIndex = limit * (page - 1);
let iterate = 0;
const newData = data.map((value: any) => {
iterate++;
value.no = startIndex + iterate;
return value;
});
console.log("daata", data);
setArticle(newData);
}
};
async function doDelete(id: any) {
// loading();
const resDelete = await deleteArticle(id);
if (resDelete?.error) {
error(resDelete.message);
return false;
}
close();
success("Success Deleted");
}
const handleDelete = (id: any) => {
MySwal.fire({
title: "Hapus Data",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#3085d6",
confirmButtonColor: "#d33",
confirmButtonText: "Hapus",
}).then((result) => {
if (result.isConfirmed) {
doDelete(id);
}
});
};
function successSubmit() {
MySwal.fire({
title: "Sukses",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then((result) => {
if (result.isConfirmed) {
// initStete();
}
});
}
const renderCell = useCallback((article: ArticleData, columnKey: Key) => {
const cellValue = article[columnKey as keyof ArticleData];
const statusColorMap: Record<string, ChipProps["color"]> = {
active: "primary",
cancel: "danger",
pending: "success",
};
switch (columnKey) {
case "actions":
return (
<div className="relative flex justify-star items-center gap-2">
<Dropdown className="lg:min-w-[150px] bg-black text-white shadow border ">
<DropdownTrigger>
<Button isIconOnly size="lg" variant="light">
<DotsYIcon className="text-default-300" />
</Button>
</DropdownTrigger>
<DropdownMenu>
{/* <DropdownItem>
<Link href={`/admin/static-page/detail/${article.id}`}>
<EyeIconMdi className="inline mr-2 mb-1" />
Detail
</Link>
</DropdownItem> */}
<DropdownItem>
<Link href={`/admin/static-page/edit/${article.id}`}>
<CreateIconIon className="inline mr-2 mb-1" size={20} />
Edit
</Link>
</DropdownItem>
<DropdownItem onClick={() => handleDelete(article.id)}>
<DeleteIcon
color="red"
width={20}
height={16}
className="inline mr-2 mb-1"
/>
Delete
</DropdownItem>
</DropdownMenu>
</Dropdown>
</div>
);
default:
return cellValue;
}
}, []);
let typingTimer: NodeJS.Timeout;
const doneTypingInterval = 1500;
const handleKeyUp = () => {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
};
const handleKeyDown = () => {
clearTimeout(typingTimer);
};
async function doneTyping() {
initState();
}
return (
<>
<div className="p-3">
<div className="flex flex-col items-start rounded-2xl gap-3">
<div className="flex flex-col md:flex-row gap-3 w-full">
<div className="flex flex-col gap-1 w-1/3">
<p className="font-semibold text-sm">Search</p>
<Input
aria-label="Search"
classNames={{
inputWrapper: "bg-default-100",
input: "text-sm",
}}
labelPlacement="outside"
startContent={
<SearchIcon className="text-base text-default-400 pointer-events-none flex-shrink-0" />
}
type="text"
onChange={(e) => setSearch(e.target.value)}
onKeyUp={handleKeyUp}
onKeyDown={handleKeyDown}
/>
</div>
<div className="flex flex-col gap-1 w-[72px]">
<p className="font-semibold text-sm">Show</p>
<Select
label=""
variant="bordered"
labelPlacement="outside"
placeholder="Select"
selectedKeys={[showData]}
className="w-full"
onChange={(e) =>
e.target.value === "" ? "" : setShowData(e.target.value)
}
>
<SelectItem key="5" value="5">
5
</SelectItem>
<SelectItem key="10" value="10">
10
</SelectItem>
</Select>
</div>
<div className="flex flex-col gap-1 w-[170px]">
<p className="font-semibold text-sm">Category</p>
<Select
label=""
variant="bordered"
labelPlacement="outside"
placeholder="Select"
selectedKeys={[showData]}
className="w-full"
onChange={(e) =>
e.target.value === "" ? "" : setShowData(e.target.value)
}
>
<SelectItem key="10" value="10">
Polda Metro Jaya
</SelectItem>
<SelectItem key="5" value="5">
Polda Sumatera Utara
</SelectItem>
</Select>
</div>
<div className="flex flex-col gap-1 w-full md:w-[340px]">
<p className="font-semibold text-sm">Date</p>
<Datepicker
value={startDateValue}
displayFormat="DD/MM/YYYY"
onChange={(e: any) => setStartDateValue(e)}
inputClassName="z-50 w-full text-sm bg-transparent border-1 border-gray-200 px-2 py-[6px] rounded-xl h-[40px] text-gray-600 dark:text-gray-300"
/>
</div>
</div>
<Table
aria-label="micro issue table"
className="rounded-3xl"
classNames={{
th: "bg-white dark:bg-black text-black dark:text-white border-b-1 text-md",
base: "bg-white dark:bg-black border",
wrapper:
"min-h-[50px] bg-transpararent text-black dark:text-white ",
}}
>
<TableHeader columns={columns}>
{(column) => (
<TableColumn key={column.uid}>{column.name}</TableColumn>
)}
</TableHeader>
<TableBody
items={article}
emptyContent={"No data to display."}
loadingContent={<Spinner label="Loading..." />}
>
{(item) => (
<TableRow key={item.id}>
{(columnKey) => (
<TableCell>{renderCell(item, columnKey)}</TableCell>
)}
</TableRow>
)}
</TableBody>
</Table>
<div className="my-2 w-full flex justify-center">
<Pagination
isCompact
showControls
showShadow
color="primary"
classNames={{
base: "bg-transparent",
wrapper: "bg-transparent",
}}
page={page}
total={totalPage}
onChange={(page) => setPage(page)}
/>
</div>
</div>
</div>
</>
);
}

View File

@ -5,7 +5,9 @@ import {
httpPost,
httpPut,
} from "./http-config/axios-base-service";
import Cookies from "js-cookie";
const token = Cookies.get("access_token");
export async function getListArticle(props: PaginationRequest) {
const { page, limit, search, startDate, endDate } = props;
const headers = {
@ -20,6 +22,7 @@ export async function getListArticle(props: PaginationRequest) {
export async function createArticle(data: any) {
const headers = {
"content-type": "application/json",
Authorization: `Bearer ${token}`,
};
const pathUrl = `/articles`;
return await httpPost(pathUrl, headers, data);

View File

@ -0,0 +1,47 @@
import { PaginationRequest } from "@/types/globals";
import {
httpDeleteInterceptor,
httpGet,
httpPost,
httpPut,
} from "./http-config/axios-base-service";
export async function createCustomStaticPage(data: any) {
const headers = {
"content-type": "application/json",
};
const pathUrl = `/custom-static-pages`;
return await httpPost(pathUrl, headers, data);
}
export async function editCustomStaticPage(data: any) {
const headers = {
"content-type": "application/json",
};
const pathUrl = `/custom-static-pages/${data.id}`;
return await httpPut(pathUrl, headers, data);
}
export async function getCustomStaticPage(props: PaginationRequest) {
const { page, limit, search } = props;
const headers = {
"content-type": "application/json",
};
return await httpGet(
`/custom-static-pages?limit=${limit}&page=${page}&title=${search}`,
headers
);
}
export async function getCustomStaticDetail(id: string) {
const headers = {
"content-type": "application/json",
};
return await httpGet(`/custom-static-pages/${id}`, headers);
}
export async function getCustomStaticDetailBySlug(slug: string) {
const headers = {
"content-type": "application/json",
};
return await httpGet(`/custom-static-pages/slug/${slug}`, headers);
}