Skip to content

Instantly share code, notes, and snippets.

View levvsha's full-sized avatar

Mikhail Shabrikov levvsha

View GitHub Profile
const decorator = new CompositeDecorator([
{
strategy: findLinkEntities,
component: Link
}
]);
this.state = {
inlineToolbar: { show: false },
editorState: EditorState.createEmpty(decorator)
setLink() {
// getting url from prompt dialogue
const urlValue = prompt('Paste URL', '');
// getting current editor state
const { editorState } = this.state;
// getting current contentState
const contentState = editorState.getCurrentContent();
// creating Entity
const contentStateWithEntity = contentState.createEntity(
'LINK',
handleKeyCommand(command) {
const { editorState } = this.state;
const newState = RichUtils.handleKeyCommand(editorState, command);
if (newState) {
this.onChange(newState);
return true;
}
return false;
<Editor
editorState={editorState}
onChange={this.onChange}
handleKeyCommand={this.handleKeyCommand}
customStyleMap={customStyleMap}
ref="editor"
/>
const customStyleMap = {
HIGHLIGHT: {
backgroundColor: 'palegreen',
},
};
onMouseDown={(e) => {
e.preventDefault();
onToggle(type.style);
}}
<InlineToolbar
editorState={editorState}
onToggle={this.toggleInlineStyle}
position={inlineToolbar.position}
/>
toggleInlineStyle(inlineStyle) {
this.onChange(
RichUtils.toggleInlineStyle(
this.state.editorState,
inlineStyle
)
);
}
onChange(editorState) {
if (!editorState.getSelection().isCollapsed()) {
const selectionRange = getSelectionRange();
if (!selectionRange) {
this.setState({ inlineToolbar: { show: false } });
return;
}
const selectionCoords = getSelectionCoords(selectionRange);
this.setState({
inlineToolbar: {
export const getSelectionCoords = (selectionRange) => {
const editorBounds = document.getElementById('editor-container').getBoundingClientRect();
const rangeBounds = selectionRange.getBoundingClientRect();
const rangeWidth = rangeBounds.right - rangeBounds.left;
// 107px is width of inline toolbar
const offsetLeft = (rangeBounds.left - editorBounds.left) + (rangeWidth / 2) - (107 / 2);
// 42px is height of inline toolbar
const offsetTop = rangeBounds.top - editorBounds.top - 42;