You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.4 KiB

4 years ago
import { Box, Button, useToast } from '@chakra-ui/react';
4 years ago
import React, { useEffect, useState } from 'react';
import { MarkdownEditor } from 'components/markdown-editor/editor';
import PageContainer from 'layouts/page-container';
4 years ago
import EditorNav from 'layouts/nav/editor-nav'
4 years ago
import { EditMode } from 'src/types/editor';
import { MarkdownRender } from 'components/markdown-editor/render';
import { Post } from 'src/types/posts';
import { requestApi } from 'utils/axios/request';
import { useRouter } from 'next/router';
4 years ago
import { config } from 'utils/config';
import { cloneDeep } from 'lodash';
4 years ago
import Card from 'components/card';
4 years ago
const content = `
# test
`
function PostEditPage() {
const router = useRouter()
4 years ago
const { id } = router.query
4 years ago
const [editMode, setEditMode] = useState(EditMode.Edit)
4 years ago
const [ar, setAr] = useState({
4 years ago
md: content,
title: ''
})
4 years ago
4 years ago
const toast = useToast()
4 years ago
useEffect(() => {
if (id && id !== 'new') {
requestApi.get(`/editor/post/${id}`).then(res => setAr(res.data))
}
4 years ago
}, [id])
4 years ago
const onMdChange = newMd => {
4 years ago
setAr({
...ar,
md: newMd
})
}
4 years ago
4 years ago
const onChange = () => {
setAr(cloneDeep(ar))
}
const onChangeTitle = title => {
if (title.length > config.posts.titleMaxLen) {
toast({
description: `Title长度不能超过${config.posts.titleMaxLen}`,
status: "error",
duration: 2000,
isClosable: true,
4 years ago
})
return
4 years ago
}
4 years ago
setAr({ ...ar, title: title })
4 years ago
}
4 years ago
const publish = async () => {
4 years ago
const res = await requestApi.post(`/editor/post`, ar)
4 years ago
toast({
4 years ago
description: "发布成功",
status: "success",
duration: 2000,
isClosable: true,
4 years ago
})
4 years ago
router.push(`/${res.data.username}/${res.data.id}`)
4 years ago
}
return (
<PageContainer
nav={<EditorNav
ar={ar}
4 years ago
onChange={onChange}
4 years ago
changeEditMode={(v) => setEditMode(v)}
4 years ago
changeTitle={(e) => onChangeTitle(e.target.value)}
4 years ago
publish={() => publish()}
/>}
>
4 years ago
{editMode === EditMode.Edit ?
<Card style={{ height: 'calc(100vh - 145px)' }}>
4 years ago
<MarkdownEditor
4 years ago
onChange={(md) => onMdChange(md)}
4 years ago
md={ar.md}
4 years ago
/></Card> :
<Card>
4 years ago
<Box height="100%" p="6">
<MarkdownRender md={ar.md} />
</Box>
4 years ago
</Card>
}
4 years ago
</PageContainer>
);
}
export default PostEditPage