@eureca/eureca-ui
Version:
UI component library of Eureca's user and admin apps
86 lines (74 loc) • 2.13 kB
JavaScript
import React, { useState, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
// Removes all HTML tags from the string
const getPlainText = strSrc => {
let resultStr = '';
// Ignore the <p> tag if it is in very start of the text
strSrc.indexOf('<p>') === 0 ? (resultStr = strSrc.substring(3)) : (resultStr = strSrc);
// Replace <p> with two newlines
resultStr = resultStr.replace(/<p>/gi, '\r\n\r\n');
// Replace <br /> with one newline
resultStr = resultStr.replace(/<br \/>/gi, '\r\n');
resultStr = resultStr.replace(/<br>/gi, '\r\n');
// Replace   with empty space
resultStr = resultStr.replace(/ /gi, '');
// -+-+-+-+-+-+-+-+-+-+-+
// Strip off other HTML tags.
// -+-+-+-+-+-+-+-+-+-+-+
return resultStr.replace(/<[^<|>]+?>/gi, '');
};
const TextEditor = ({
data,
isDisabled,
onInitEditor,
onChange,
onBlur,
onFocus,
className,
...props
}) => {
const editorRef = useRef();
const [editorLoaded, setEditorLoaded] = useState(false);
const { CKEditor, ClassicEditor } = editorRef.current || {};
useEffect(() => {
editorRef.current = {
CKEditor: require('@ckeditor/ckeditor5-react'),
ClassicEditor: require('@ckeditor/ckeditor5-build-classic'),
};
setEditorLoaded(true);
}, []);
return editorLoaded ? (
<CKEditor
className={className}
editor={ClassicEditor}
data={data}
onChange={(event, editor) => {
const data = editor.getData();
const plainText = getPlainText(data);
onChange && onChange(event, data, plainText);
}}
onBlur={editor => {
onBlur && onBlur(editor);
}}
onFocus={editor => {
onFocus && onFocus(editor);
}}
{...props}
/>
) : null;
};
TextEditor.defaultProps = {
data: '',
onChange: () => {},
onBlur: () => {},
onFocus: () => {},
className: '',
};
TextEditor.propTypes = {
data: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
onChange: PropTypes.func,
onBlur: PropTypes.func,
onFocus: PropTypes.func,
className: PropTypes.string,
};
export { TextEditor };