-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveAnnotationsSource.js
75 lines (65 loc) · 2.43 KB
/
RemoveAnnotationsSource.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
const React = window.React;
const Modifier = window.DraftJS.Modifier;
const EditorState = window.DraftJS.EditorState;
const SelectionState = window.DraftJS.SelectionState;
class RemoveAnnotationSource extends React.Component {
componentDidMount() {
const { editorState,
onComplete
} = this.props;
var contentState = editorState.getCurrentContent();
console.log("Block map before entity removal/rendering:", contentState.getBlockMap());
const rangesToRemove = [];
contentState.getBlockMap().forEach(contentBlock => {
contentBlock.findEntityRanges(character => {
// FILTER
if (character.getEntity() !== null) {
const entityKey = character.getEntity();
const entity = contentState.getEntity(entityKey);
if (entity && entity.getType() === 'ANNOTATION') {
return true;
}
}
return false;
},
// CALLBACK
(start, end) => {
const blockKey = contentBlock.getKey();
rangesToRemove.push([start, end, blockKey]);
}
);
});
// current content saved as base new content state
// removes already annotated ranges (if annotation called on already annotated text!)
let currentContent = editorState.getCurrentContent();
rangesToRemove.forEach(range => {
const start = range[0];
const end = range [1];
const blockKey = range[2];
const blockSelection = SelectionState
.createEmpty(blockKey)
.merge({
anchorOffset: start,
focusOffset: end,
});
currentContent = Modifier.applyEntity(
currentContent,
blockSelection,
null
);
});
console.log(`Removed ${rangesToRemove.length} annotations.`);
// Create the new state as an undoable action.
const nextState = EditorState.push(
editorState,
currentContent,
"apply-entity"
);
// render next state through onComplete DraftTail method
onComplete(nextState);
}
render() {
return null;
}
}
module.exports = RemoveAnnotationSource;