little update

This commit is contained in:
Rama Priyanto 2024-12-23 00:58:20 +07:00
parent 4e7eb26fd8
commit a4f94e1c3a
1 changed files with 284 additions and 282 deletions

View File

@ -1,298 +1,300 @@
'use client' "use client";
import { getArticleById } from '@/service/article'; import { getArticleById } from "@/service/article";
import { zodResolver } from '@hookform/resolvers/zod'; import { zodResolver } from "@hookform/resolvers/zod";
import { Button, Card, Chip, Input, Select, SelectItem, Selection } from '@nextui-org/react'; import {
import JoditEditor from 'jodit-react'; Button,
import Link from 'next/link'; Card,
import { usePathname } from 'next/navigation'; Chip,
import React, { useEffect, useRef, useState } from 'react'; Input,
import { useForm } from 'react-hook-form'; Select,
import Swal from 'sweetalert2'; SelectItem,
import withReactContent from 'sweetalert2-react-content'; Selection,
} from "@nextui-org/react";
import JoditEditor from "jodit-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import React, { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import * as z from "zod"; import * as z from "zod";
const articleSchema = z.object({ const articleSchema = z.object({
title: z.string().min(1, { message: "Required" }), title: z.string().min(1, { message: "Required" }),
article: z.string().min(1, { message: "Required" }), article: z.string().min(1, { message: "Required" }),
slug: z.string().min(1, { message: "Required" }), slug: z.string().min(1, { message: "Required" }),
tags: z.string().min(0, { message: "Required" }).optional(), tags: z.string().min(0, { message: "Required" }).optional(),
description: z.string().min(1, { message: "Required" }).optional(), description: z.string().min(1, { message: "Required" }).optional(),
}); });
export default function FormUpdateArticle() { export default function FormUpdateArticle() {
// const [id, setId] = useState<any>(); // const [id, setId] = useState<any>();
const [title, setTitle] = useState<string>(""); const [title, setTitle] = useState<string>("");
const [slug, setSlug] = useState<string>(""); const [slug, setSlug] = useState<string>("");
const [tags, setTags] = useState<string[]>([]); const [tags, setTags] = useState<string[]>([]);
const [newTags, setNewTags] = useState<string>(""); const [newTags, setNewTags] = useState<string>("");
const editor = useRef(null); const editor = useRef(null);
const [content, setContent] = useState(''); const [content, setContent] = useState("");
const MySwal = withReactContent(Swal); const MySwal = withReactContent(Swal);
const [article, setArticle] = useState<any>(); const [article, setArticle] = useState<any>();
const [typeId, setTypeId] = React.useState<Selection>(new Set([])); const [typeId, setTypeId] = useState("");
const pathname = usePathname(); const pathname = usePathname();
const splitPathname = pathname.split('/'); const splitPathname = pathname.split("/");
const id = splitPathname[splitPathname.length - 1]; const id = splitPathname[splitPathname.length - 1];
console.log(id, "pathnamesplit") console.log(id, "pathnamesplit");
const formOptions = { resolver: zodResolver(articleSchema) }; const formOptions = { resolver: zodResolver(articleSchema) };
type MicroIssueSchema = z.infer<typeof articleSchema>; type MicroIssueSchema = z.infer<typeof articleSchema>;
const { const {
register, register,
control, control,
handleSubmit, handleSubmit,
setValue, setValue,
formState: { errors }, formState: { errors },
} = useForm<MicroIssueSchema>(formOptions); } = useForm<MicroIssueSchema>(formOptions);
const editorConfig = { const editorConfig = {
readonly: true, readonly: true,
};
const TypeId = [
{
key: 1,
label: "Article",
},
{
key: 2,
label: "Magazine",
},
];
const CategoryArticle = [
{
key: 1,
label: "Article",
},
{
key: 2,
label: "Magazine",
},
];
const handleClose = (tagsToRemove: string) => {
setTags(tags.filter((tag) => tag !== tagsToRemove));
if (tags.length === 1) {
setTags([]);
}
};
const handleAddTags = (e: any) => {
if (newTags.trim() !== "") {
setTags([...tags, newTags.trim()]);
setNewTags("");
e.preventDefault();
}
};
const handleKeyDown = (event: any) => {
if (event.key === "Enter") {
handleAddTags(event);
}
};
useEffect(() => {
async function initState() {
const res = await getArticleById(id);
setArticle(res.data?.data);
setTitle(res.data?.data?.title);
setTypeId(res.data?.data?.typeId);
setSlug(res.data?.data?.slug);
const tagsArray = res.data.data?.tags
? res.data.data.tags.split(",")
: [];
setTags(tagsArray);
console.log("Data Aritcle", res.data?.data);
} }
const TypeId = [ initState();
{ }, []);
key: 1,
label: "Article"
},
{
key: 2,
label: "Magazine"
},
]
const CategoryArticle = [ async function save(data: any) {
{ const formData = {
key: 1, id: id,
label: "Article" title: title,
}, typeId: parseInt(String(Array.from(article)[0])),
{ slug: slug,
key: 2, tags: tags.join(","),
label: "Magazine" description: content,
}, htmlDescription: content,
]
const handleClose = (tagsToRemove: string) => {
setTags(tags.filter((tag) => tag !== tagsToRemove));
if (tags.length === 1) {
setTags([]);
}
}; };
const handleAddTags = (e: any) => { console.log("Form Data:", formData);
if (newTags.trim() !== "") { // const response = await createArticle(formData);
setTags([...tags, newTags.trim()]);
setNewTags("");
e.preventDefault();
}
};
const handleKeyDown = (event: any) => { // if (response?.error) {
if (event.key === "Enter") { // error(response.message);
handleAddTags(event); // return false;
} // }
}; }
async function onSubmit(data: any) {
useEffect(() => { MySwal.fire({
async function initState() { title: "Simpan Data",
const res = await getArticleById(id); text: "",
setArticle(res.data?.data); icon: "warning",
setTitle(res.data?.data?.title) showCancelButton: true,
setTypeId(res.data?.data?.typeId) cancelButtonColor: "#d33",
setSlug(res.data?.data?.slug) confirmButtonColor: "#3085d6",
const tagsArray = res.data.data?.tags ? res.data.data.tags.split(",") : []; confirmButtonText: "Simpan",
setTags(tagsArray); }).then((result) => {
if (result.isConfirmed) {
console.log("Data Aritcle", res.data?.data); save(data);
} }
});
initState(); }
}, []); return (
<div className="mx-5 my-5 overflow-y-auto">
<form method="POST" onSubmit={handleSubmit(onSubmit)}>
async function save(data: any,) { <Card className="rounded-md p-5 space-y-5">
const formData = { <div>
id: id, <Input
title: title, type="title"
typeId: parseInt(String(Array.from(article)[0])), {...register("title")}
slug: slug, value={title}
tags: tags.join(','), onValueChange={setTitle}
description: content, label="Judul"
htmlDescription: content variant="bordered"
}; placeholder="Enter Text"
labelPlacement="outside"
console.log("Form Data:", formData); />
// const response = await createArticle(formData); <div className="text-sm text-red-500">
{title?.length > 0 && errors.title && errors.title.message}
// if (response?.error) { </div>
// error(response.message); </div>
// return false; <div>
// } <Select
}; label="Jenis Artikel"
{...register("article")}
async function onSubmit(data: any) { selectedKeys={[typeId]}
MySwal.fire({ onChange={(e) => setTypeId(e.target.value)}
title: "Simpan Data", variant="bordered"
text: "", labelPlacement="outside"
icon: "warning", placeholder="Select"
showCancelButton: true, className="max-w-xs"
cancelButtonColor: "#d33", >
confirmButtonColor: "#3085d6", {TypeId.map((data) => (
confirmButtonText: "Simpan", <SelectItem key={data.key} value={data.key}>
}).then((result) => { {data.label}
if (result.isConfirmed) { </SelectItem>
save(data); ))}
} </Select>
}); <div className="text-sm text-red-500">
} {errors.article?.message}
return ( </div>
<div className='mx-5 my-5 overflow-y-auto'> </div>
<form method="POST" onSubmit={handleSubmit(onSubmit)}> <div>
<Card className='rounded-md p-5 space-y-5'> <Input
<div> type="text"
<Input {...register("slug")}
type="title" value={slug}
{...register("title")} onValueChange={setSlug}
value={title} label="Slug"
onValueChange={setTitle} variant="bordered"
label="Judul" placeholder="Enter Text"
variant='bordered' labelPlacement="outside"
placeholder="Enter Text" />
labelPlacement='outside' <div className="text-sm text-red-500">
/> {slug?.length > 0 && errors.slug && errors.slug.message}
<div className="text-sm text-red-500"> </div>
{(title?.length > 0 && errors.title) && errors.title.message} </div>
</div> <div>
</div> <Input
<div> label="Tags (Optional)"
<Select {...register("tags")}
label="Jenis Artikel" labelPlacement="outside"
{...register("article")} type="text"
selectedKeys={typeId} value={newTags}
onSelectionChange={setTypeId} onChange={(e) => setNewTags(e.target.value)}
variant="bordered" onKeyDown={handleKeyDown}
labelPlacement='outside' placeholder="Tambahkan tag baru dan tekan Enter"
placeholder="Select" />
className="max-w-xs" <div className="text-sm text-red-500">
> {tags.length === 0 && errors.tags && errors.tags.message}
{TypeId.map((data) => ( </div>
<SelectItem key={data.key} value={data.key}> <div className="flex gap-2 border border-inherit mt-2 rounded-md p-1 items-center h-11">
{data.label} {tags.map((tag, index) => (
</SelectItem> <Chip
))} key={index}
</Select> color="primary"
<div className="text-sm text-red-500"> onClose={() => handleClose(tag)}
{errors.article?.message} >
</div> {tag}
{/* <p>{article}</p> */} </Chip>
</div> ))}
<div> </div>
<Input </div>
type="text" <div>
{...register("slug")} <p className="pb-2">Description</p>
value={slug} <JoditEditor
onValueChange={setSlug} ref={editor}
label="Slug" value={article?.description}
variant='bordered' onChange={(newContent) => setContent(newContent)}
placeholder="Enter Text" className="dark:text-black"
labelPlacement='outside' />
/> <div className="text-sm text-red-500">
<div className="text-sm text-red-500"> {content.length === 0 &&
{(slug?.length > 0 && errors.slug) && errors.slug.message} errors.description &&
</div> errors.description.message}
</div> </div>
<div> </div>
<Input <div>
label="Tags (Optional)" <p>Attachment (Opsional)</p>
{...register("tags")} <div className="flex items-center justify-center w-full pt-2 ">
labelPlacement='outside' <label
type="text" htmlFor="dropzone-file"
value={newTags} className="flex flex-col items-center justify-center w-full h-36 border border-gray-100 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 dark:border-gray-600 dark:hover:border-gray-500 dark:hover:bg-gray-200"
onChange={(e) => setNewTags(e.target.value)} >
onKeyDown={handleKeyDown} <div className="flex flex-col items-center justify-center pt-5 pb-6 ">
placeholder="Tambahkan tag baru dan tekan Enter" <svg
/> className="w-10 h-10 mb-3 text-gray-400"
<div className="text-sm text-red-500"> fill="none"
{(tags.length === 0 && errors.tags) && errors.tags.message} stroke="currentColor"
</div> viewBox="0 0 24 24"
<div className="flex gap-2 border border-inherit mt-2 rounded-md p-1 items-center h-11"> xmlns="http://www.w3.org/2000/svg"
{tags.map((tag, index) => ( >
<Chip key={index} color='primary' onClose={() => handleClose(tag)}> <path
{tag} strokeLinecap="round"
</Chip> strokeLinejoin="round"
))} strokeWidth="2"
</div> d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
</div> ></path>
<div> </svg>
<p className='pb-2'>Description</p> <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
<JoditEditor Drag and drop files here
ref={editor} </p>
value={article?.description} <p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
// config={editorConfig} <span className="font-semibold underline text-amber-800">
onChange={(newContent) => setContent(newContent)} Click to upload
className="dark:text-black" </span>
</p>
/> </div>
<div className="text-sm text-red-500"> <input id="dropzone-file" type="file" />
{(content.length === 0 && errors.description) && errors.description.message} </label>
</div> </div>
</div> </div>
<div> <div className="flex justify-end gap-3">
<p>Attachment (Opsional)</p> <Link href={`/admin/article`}>
<div className="flex items-center justify-center w-full pt-2 "> <Button color="danger" variant="ghost">
<label Cancel
htmlFor="dropzone-file" </Button>
className="flex flex-col items-center justify-center w-full h-36 border border-gray-100 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 dark:border-gray-600 dark:hover:border-gray-500 dark:hover:bg-gray-200" </Link>
> <Button type="submit" color="primary" variant="solid">
<div className="flex flex-col items-center justify-center pt-5 pb-6 "> Publish
<svg </Button>
className="w-10 h-10 mb-3 text-gray-400" </div>
fill="none" </Card>
stroke="currentColor" </form>
viewBox="0 0 24 24" </div>
xmlns="http://www.w3.org/2000/svg" );
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"
></path>
</svg>
<p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
Drag and drop files here
</p>
<p className="mb-2 text-sm text-gray-500 dark:text-gray-400">
{/* or{" "} */}
<span className="font-semibold underline text-amber-800">
Click to upload
</span>
</p>
</div>
<input id="dropzone-file" type="file" />
</label>
</div>
</div>
<div className='flex justify-end gap-3'>
<Link href={`/admin/article`}>
<Button
color='danger'
variant="ghost"
>
Cancel
</Button>
</Link>
<Button
type="submit"
color='primary'
variant="solid"
>
Publish
</Button>
</div>
</Card>
</form>
</div>
)
} }