/
SidenoteButton.jsx
90 lines (75 loc) · 2.09 KB
/
SidenoteButton.jsx
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
import React, { Component } from 'react';
import { Modifier, EditorState } from 'draft-js';
import EditorUtils from 'draft-js-plugins-utils';
import classNames from 'classnames';
class SidenoteButton extends Component {
preventBubblingUp = (event) => { event.preventDefault(); }
isSidenoteEntityActive = () => {
return EditorUtils.hasEntity(this.props.getEditorState(), 'SIDENOTE');
}
removeSidenoteAtSelection = () => {
const editorState = this.props.getEditorState();
const nextContentState = Modifier.applyEntity(
editorState.getCurrentContent(),
editorState.getSelection(),
null // Using a 'null' entity key deletes all entites in the selection
);
this.props.setEditorState(
EditorState.push(
editorState,
nextContentState,
'apply-entity'
)
);
}
addSidenoteAtSelection = () => {
const editorState = this.props.getEditorState();
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
'SIDENOTE',
'MUTABLE',
{}
);
const nextContentState = Modifier.applyEntity(
contentStateWithEntity,
editorState.getSelection(),
contentState.getLastCreatedEntityKey()
);
this.props.setEditorState(
EditorState.push(
editorState,
nextContentState,
'apply-entity'
)
);
}
toggleSidenote = () => {
event.preventDefault();
event.stopPropagation();
if (this.isSidenoteEntityActive()) {
this.removeSidenoteAtSelection();
} else {
this.addSidenoteAtSelection();
}
}
render() {
const { theme, children } = this.props;
const className = classNames(theme.button, {
[theme.active]: this.isSidenoteEntityActive()
});
return (
<div
className={theme.buttonWrapper}
onMouseDown={this.preventBubblingUp}
>
<button
className={className}
onClick={this.toggleSidenote}
type="button"
children={children}
/>
</div>
);
}
}
export default SidenoteButton;