-
Notifications
You must be signed in to change notification settings - Fork 1
/
state.js
69 lines (63 loc) · 2.48 KB
/
state.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
import React, { Component } from 'react';
import { Raw, Plain, resetKeyGenerator } from 'slate';
import { batch } from '../utils/batch';
const parseValue = (value, initialState, terse) => {
resetKeyGenerator();
try { return Raw.deserialize(value, { terse }); }
catch(err) {
try { return Raw.deserialize(value, { terse: !terse }); }
catch(err) {
return initialState ? parseValue(initialState, undefined, { terse }) : Plain.deserialize('');
}
}
};
const defaultGetValue = ({ value }) => value;
const defaultChangeValue = ({ onChange }, value) => onChange ? onChange(value) : null;
export default ({ getValue = defaultGetValue, changeValue = defaultChangeValue, initialState, terse } = {}) => {
return Editor => class SlateStateDecorator extends Component {
static propTypes = { }
isFocused = false;
batch = batch(300);
rawValue = null;
constructor(props) {
super();
this.rawValue = getValue(props);
this.value = parseValue(this.rawValue, initialState, terse);
}
shouldComponentUpdate(props) {
const newValue = getValue(props);
const oldValue = getValue(this.props);
if (newValue !== oldValue && this.rawValue !== newValue) {
this.value = parseValue(newValue, undefined, terse);
return true;
}
if (props.readOnly !== this.props.readOnly) return true;
return false;
}
changeValue = (value) => {
this.value = value;
this.forceUpdate();
if (changeValue) {
const rawValue = Raw.serialize(value, { terse });
if (JSON.stringify(this.rawValue) !== JSON.stringify(rawValue)) {
this.rawValue = rawValue;
this.batch(() => {
if (rawValue.nodes.length === 1 && rawValue.nodes[0].nodes.length === 1 && (!rawValue.nodes[0].nodes[0].text && !rawValue.nodes[0].nodes[0].isVoid)) {
// if (rawValue.nodes.length === 1 && rawValue.nodes[0].kind === 'text' && !rawValue.nodes[0].text) {
changeValue(this.props, null);
// } else if (rawValue.nodes.length === 1 && rawValue.nodes[0].type === 'paragraph' && (!rawValue.nodes.length || (rawValue.nodes[0].nodes[0].kind === 'text' && !rawValue.nodes[0].nodes[0].text))) {
// changeValue(this.props, null);
} else {
changeValue(this.props, rawValue);
}
});
}
}
}
render() {
return (
<Editor {...this.props} value={this.value} onChange={this.changeValue} />
);
}
};
};