forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (92 loc) · 1.99 KB
/
index.js
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import { Editor } from 'slate-react'
import { Block, Value } from 'slate'
import { CHILD_REQUIRED, CHILD_TYPE_INVALID } from 'slate-schema-violations'
import React from 'react'
import initialValue from './value.json'
/**
* A simple schema to enforce the nodes in the Slate document.
*
* @type {Object}
*/
const schema = {
document: {
nodes: [
{ types: ['title'], min: 1, max: 1 },
{ types: ['paragraph'], min: 1 },
],
normalize: (change, violation, { node, child, index }) => {
switch (violation) {
case CHILD_TYPE_INVALID: {
return change.setNodeByKey(
child.key,
index == 0 ? 'title' : 'paragraph'
)
}
case CHILD_REQUIRED: {
const block = Block.create(index == 0 ? 'title' : 'paragraph')
return change.insertNodeByKey(node.key, index, block)
}
}
},
},
}
/**
* The Forced Layout example.
*
* @type {Component}
*/
class ForcedLayout extends React.Component {
/**
* Deserialize the initial editor value.
*
* @type {Object}
*/
state = {
value: Value.fromJSON(initialValue),
}
/**
* On change.
*
* @param {Change} change
*/
onChange = ({ value }) => {
this.setState({ value })
}
/**
* Render the editor.
*
* @return {Component} component
*/
render() {
return (
<div className="editor">
<Editor
placeholder="Enter a title..."
value={this.state.value}
schema={schema}
onChange={this.onChange}
renderNode={this.renderNode}
/>
</div>
)
}
/**
* Render a Slate node.
*
* @param {Object} props
* @return {Element}
*/
renderNode = props => {
const { attributes, children, node } = props
switch (node.type) {
case 'title':
return <h2 {...attributes}>{children}</h2>
case 'paragraph':
return <p {...attributes}>{children}</p>
}
}
}
/**
* Export.
*/
export default ForcedLayout