forked from vercel/next.js
/
index.tsx
51 lines (48 loc) · 1.37 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { useState } from 'react'
import { createEditor, Descendant } from 'slate'
import { Slate, Editable, withReact } from 'slate-react'
import { withHistory } from 'slate-history'
import { InferGetServerSidePropsType } from 'next'
export async function getServerSideProps() {
return {
props: {
editorState: [
{
children: [
{ text: 'This is editable plain text, just like a <textarea>!' },
],
},
],
},
}
}
async function saveEditorState(edtorState: Descendant[]) {
const response = await fetch('/api/editor-state', {
method: 'POST',
body: JSON.stringify(edtorState),
})
return response.json()
}
export default function IndexPage({
editorState,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
const [editor] = useState(() => withReact(withHistory(createEditor())))
return (
<Slate
editor={editor}
value={editorState}
onChange={async (value) => {
const isAstChange = editor.operations.some(
(op) => 'set_selection' !== op.type
)
if (isAstChange) {
// You might want to debounce the following call!
const responseData = await saveEditorState(value)
console.log('Send editor state to the server', responseData)
}
}}
>
<Editable placeholder="Enter some plain text..." />
</Slate>
)
}