80 lines
2.9 KiB
TypeScript
80 lines
2.9 KiB
TypeScript
'use client'
|
|
import { ReactNode } from "react"
|
|
import TableGen from "../TableGen"
|
|
import { Attributes } from "@sequelize/core";
|
|
import { Post } from "@/model/Post";
|
|
import { useState } from "react";
|
|
|
|
type Actions = {
|
|
deletePost:any
|
|
getPosts:()=>Promise<string>
|
|
}
|
|
|
|
type Props = {
|
|
children?:ReactNode;
|
|
headings:Array<string>;
|
|
data:any[];
|
|
actions?:Actions;
|
|
}
|
|
|
|
type EditorProps = {
|
|
open:boolean;
|
|
post?:Attributes<Post>;
|
|
}
|
|
|
|
function RenderEditor(props:EditorProps){
|
|
let [content,setContent] = useState(props.post?.content)
|
|
let [title,setTitle] = useState(props.post?.title)
|
|
|
|
return <form className="bg-light w-[100%] h-content p-1">
|
|
<h1 className="m-2">Edit Post</h1>
|
|
<h2 className="m-2">Title</h2>
|
|
<input value={title} onChange={e => setTitle(e.target.value)} type='text' className="m-2"></input>
|
|
<h2 className="m-2">Content</h2>
|
|
<textarea value={content} onChange={e => setContent(e.target.value)} className="w-[100%] h-content align-top text-start text-base line-clamp-6 m-2"></textarea>
|
|
<button type="button" className="m-2 btn btn-primary">Preview</button>
|
|
<button type="button" className="m-2 btn btn-success">Save</button>
|
|
<button type="button" className="m-2 btn btn-danger">Cancel</button>
|
|
</form>
|
|
}
|
|
|
|
|
|
export default function PostTable(props:Props){
|
|
|
|
function showEditor(entry:Attributes<Post>){
|
|
setEditor({
|
|
open: true,
|
|
post: entry
|
|
})
|
|
}
|
|
const initEditorState:EditorProps = {
|
|
open: false
|
|
}
|
|
const [posts, setPosts] = useState(props.data);
|
|
const [editor, setEditor] = useState(initEditorState)
|
|
|
|
function deletePost(entry:Attributes<Post>){
|
|
props.actions?.deletePost(entry.id);
|
|
props.actions?.getPosts().then((p)=>setPosts(JSON.parse(p)));
|
|
}
|
|
|
|
|
|
return <>
|
|
<TableGen headings={props.headings}>
|
|
{posts.map((d)=>{
|
|
return <><tr key={d.id}>
|
|
<th scope="row">{d.id}</th>
|
|
<td key='titlefield'>{d.title}</td>
|
|
<td key='contentfield'>{d.content.length<255 ? d.content :`${d.content.substring(0,255)}...`}</td>
|
|
<td key='createdatfield'>{d.createdAt}</td>
|
|
<td key='updatedatfield'>{d.updatedAt}</td>
|
|
<td key='btnedit'><button type="button" className="btn btn-primary" onClick={()=>showEditor(d)}>Edit</button></td>
|
|
<td key='btndelete'><button type="button" className="btn btn-danger" onClick={()=>deletePost(d)}> Delete</button></td>
|
|
</tr>
|
|
{(editor.open && editor.post && editor.post.id == d.id)?
|
|
<tr key={'activeEditor'}><th scope="row" colSpan={props.headings.length}><RenderEditor open={editor.open} post={editor.post}></RenderEditor></th></tr>:""}
|
|
</>
|
|
})}
|
|
</TableGen>
|
|
</>
|
|
} |