import { posts, type BlogPost } from "../lib/post"; import { useRef, useState } from "react"; import { useNavigate } from "react-router"; import { useSearchParams } from "react-router"; import { ContentState, convertFromRaw, convertToRaw, Editor, EditorState, RichUtils, } from "draft-js"; import "draft-js/dist/Draft.css"; export function BlogPostForm({ post, onSubmit, }: { post: BlogPost | null; onSubmit: (post: BlogPost) => void; }) { const [postState, setPostState] = useState({ id: post?.id ?? posts.length, title: post?.title ?? "", summary: post?.summary ?? "", content: post?.content ?? "", author: post?.author ?? "", datePosted: post?.datePosted ?? new Date().toISOString().split("T")[0], }); const [missing, setMissing] = useState([]); const [contentState, setContentState] = useState(() => { if (post?.content) { try { const rawContent = JSON.parse(post.content); return EditorState.createWithContent(convertFromRaw(rawContent)); } catch { // Fallback to plain text if JSON parsing fails return EditorState.createWithContent( ContentState.createFromText(post.content), ); } } return EditorState.createEmpty(); }); const editorRef = useRef(null); const navigate = useNavigate(); const handleChange = ( event: React.ChangeEvent, ) => { const { name, value } = event.target; setPostState((prevState) => ({ ...prevState, [name]: value })); }; const handleMissing = () => { const missingFields = Object.entries(postState) .map(([key, value]) => (value === "" ? key : null)) .filter((key) => key !== null); setMissing(missingFields); }; const handleContentChange = (content: EditorState) => { setContentState(content); const rawContent = convertToRaw(content.getCurrentContent()); setPostState((prevState) => ({ ...prevState, content: JSON.stringify(rawContent), })); }; const handleInlineStyle = (style: string) => { setContentState((prevState) => RichUtils.toggleInlineStyle(prevState, style), ); }; const handleSubmit = (event: React.MouseEvent) => { event.preventDefault(); if ( !postState.title || !postState.summary || !postState.content || !postState.author ) { handleMissing(); return; } onSubmit(postState); navigate("/"); }; return (
{missing.includes("title") && (

Title is required

)}