I use highlight.js to enable syntax highliting in draft.js editor,but when type three quotes to toggle code-block my cursor moves in two steps left and I can type only in the first string.When I try to press enter to move to the next string,my cursor just moves in the beginning of the first string.Here is my code:
import React, {FC, useRef, useState} from 'react';
import styles from './editor.module.scss';
import PluginEditor from '@draft-js-plugins/editor';
import Editor from '@draft-js-plugins/editor';
import {
AtomicBlockUtils,
EditorState,
RichUtils,
DefaultDraftBlockRenderMap, genKey,
} from 'draft-js';
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
const ArticleEditor: FC = () => {
const [editorState, setEditorState] = useState(
() => EditorState.createEmpty(),
);
const onEditorStateChange = (editorState: EditorState) => {
setEditorState(editorState);
};
const currentContent = editorState.getCurrentContent();
const selection = editorState.getSelection();
const block = currentContent.getBlockForKey(selection.getStartKey());
const currentInlineStyle = editorState.getCurrentInlineStyle();
const blockText = block.getText();
const symbolCount = blockText.split('#').length;
let starCount = blockText.split('*').length;
let hyphenCount = blockText.split('_').length;
let tildeCount = blockText.split('~').length;
const quoteCount = blockText.split('`').length;
hljs.registerLanguage('javascript', javascript);
const keyBindingFn = (event: React.KeyboardEvent<NonNullable<unknown>>) => {
switch (event.key) {
case '`':
if (quoteCount % 3 == 0) {
onEditorStateChange(RichUtils.toggleBlockType(editorState, 'code-block'));
} else if (quoteCount % 6 == 0) {
onEditorStateChange(RichUtils.toggleBlockType(editorState, 'unstyled'));
}
break;
};
const CodeBlock = (props: { block: any; contentState: any; }) => {
const { block, contentState } = props;
const key = genKey();
const language = contentState.getBlockForKey(block.key).getData().get('language') || 'javascript';
const code = contentState.getBlockForKey(block.key).getText();
const highlightedCode = hljs.highlight(language, code).value;
return <pre key={key}><code dangerouslySetInnerHTML={{ __html: highlightedCode }} /></pre>;
};
const blockRenderer = (block: { getType: () => string; }) => {
if (block.getType() === 'code-block') {
return {
component: CodeBlock,
editable: true,
};
}
return null;
};
return (
<>
<div className={styles.article__editor} onClick={event => handleClick(event)}
onFocus={focus}>
<Editor
blockRenderMap={extendedBlockRenderMap}
editorState={editorState}
onChange={onEditorStateChange}
keyBindingFn={(event) => keyBindingFn(event)}
plugins={plugins}
ref={editorRef}
blockRendererFn={blockRenderer}
/>
</div>
);
};
I will be very appriciated for any help.
I tried to set html string directly to the editorState but it doesn`t work