123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import React, { useState, useRef, useEffect, useCallback } from 'react';
- import E from 'wangeditor';
- // import PreviewMenu from './PreviewMenu'
- import Preview from './Preview';
- import { uploadImage } from '@/utils/uploadFile';
-
- export default (props) => {
- const ref = useRef();
- const editorRef = useRef();
- const [preview, setPreview] = useState(false);
- // const [content, setContent] = useState()
-
- const inited = useRef(false);
- const handleChange = useCallback(
- (html) => {
- if ((inited.current || html) && typeof props.onChange === 'function') {
- inited.current = true;
- props.onChange(html);
- }
- },
- [props],
- );
-
- const initEditor = useCallback(() => {
- const editor = new E(ref.current);
- editorRef.current = editor;
-
- // 取消自动 focus
- editor.config.focus = false;
-
- // 触发 change
- editor.config.onchange = handleChange;
-
- editor.config.zIndex = 100;
-
- // 自定义图片上传
- editor.config.uploadImgMaxLength = 1;
- editor.config.customUploadImg = (files, insert) => {
- if (!files.length) return;
-
- uploadImage(files[0]).then(insert);
- };
-
- // 扩展预览按钮
- // editor.menus.extend('previewMenu', PreviewMenu)
- // PreviewMenu.preview = (html) => setPreview(true)
-
- // 配置菜单
- editor.config.menus = [
- 'head', // 标题
- 'bold', // 粗体
- 'fontSize', // 字号
- 'fontName', // 字体
- 'italic', // 斜体
- 'underline', // 下划线
- 'strikeThrough', // 删除线
- 'foreColor', // 文字颜色
- 'backColor', // 背景颜色
- 'list', // 列表
- 'justify', // 对齐方式
- 'quote', // 引用
- 'image', // 插入图片
- 'undo', // 撤销
- 'redo', // 重复
- // 'previewMenu'
- ];
-
- // 过滤 word 字符
- editor.config.pasteFilterStyle = false;
- editor.config.pasteTextHandle = (ctt) => {
- const regs = [
- /<!--\[if [\s\S]*?endif\]-->/gi,
- /<[a-zA-Z0-9]+:[^>]+>[^>]*<\/[a-zA-Z0-9]+:[^>]+>/gi,
- /<[a-zA-Z0-9]+:[^>]+\/>/gi,
- /<style>[\s\S]*?<\/style>/gi,
- new RegExp('\u2029', 'ig'), // 替换word分隔符 序号 8233
- ];
-
- return regs.reduce((acc, reg) => {
- return acc.replace(reg, '');
- }, ctt);
- };
-
- editor.create();
- editor.$textElem.attr('contenteditable', props.contenteditable !== false);
-
- return () => editor.destroy();
- }, [props, handleChange]);
-
- useEffect(() => {
- initEditor();
- }, [initEditor]);
-
- //
- useEffect(() => {
- if (props.value && !inited.current && editorRef.current) {
- inited.current = true;
- editorRef.current.txt.html(props.value);
- }
- }, [props.value]);
-
- return (
- <>
- <div ref={ref} style={{ textAlign: 'left' }} />
- <Preview
- width={426}
- style={{ width: '426px', height: '863px', margin: 0, padding: 0 }}
- visible={preview}
- html={props.value}
- onCancel={() => setPreview(false)}
- />
- </>
- );
- };
|