最近完成了我们的社区模块,想要发送帖子,必须要有个富文本编辑器,经过选型发现wangeditor比较简单易用。不过也发现它的菜单封装有点过度,图标没法自定义,很多功能也不是想要的。那么就只能重写一部分,封装一下。
基本原理
富文本编辑器通过contenteditable来使得dom像文本那样可以编辑。通过dom的range来判断位置,插入dom。通过document.execCommand执行各种range的操作。
代码
wangeditor的菜单想要重写,可以通过继承它的基本菜单类,再注册,当前版本 “wangeditor”: “^4.0.8”,代码如下:
import React, {useState,useEffect} from 'react';
import {constance} from "./publicFunctions"
import E from 'wangeditor';
import store from '../store/store';
const { $ } = E;
const { BtnMenu, DropListMenu, PanelMenu, DropList, Panel, Tooltip } = E;
let editor = null;
let fontColorList=["#000000","#FF3D1F","#28AA55","#FFA319","#D76ED2","#BF4F17","#A5B95A","#867BD2","#39A1E6"];//文字颜色配置
let mimadaoEmoji=[//配置表情包
require("../static/emoji/AiMa-好哦表情包!.gif"),
...//图片地址
];
let fontSizeList=[{//字体大小配置1-7
name:"极小",
iconSize:"13px",
value:'2'
},{
name:"小",
iconSize:"16px",
value:'3'
},{
name:"中等",
iconSize:"18px",
value:'4'
},{
name:"大",
iconSize:"24px",
value:'5'
},{
name:"特大",
iconSize:"32px",
value:'6'
},{
name:"极大",
iconSize:"48px",
value:'7'
},];
let emojiList=[//配置表情包切换
{
// tab 的标题
title:"密码岛",
// type -> 'emoji' / 'image'
type:"image",
// content -> 数组
content:mimadaoEmoji.map(val=>{return {alt:"",src:val}})
},{
title: 'emoji',
type: 'emoji',
content: '😀 😃 😄 😁 😆 😅 😂 😊 😇 🙂 🙃 😉 😓 😪 😴 🙄 🤔 😬 🤐'.split(/\s/),
},
]
let configEditorMenu=[{//解析器模式自定义菜单
key:"alignLeft",//唯一标识菜单
type:BtnMenu,//被继承的菜单类型
elem:`
`,
command:"justifyLeft",
eventEnum:{
tryChangeActive:function(){
const editor = this.editor
if (editor.cmd.queryCommandState('justifyLeft')) {
this.active()
} else {
this.unActive()
}
}
}
},{
key:"aligncenter",
type:BtnMenu,
elem:`
`,
command:"justifyCenter",
eventEnum:{
tryChangeActive:function(){
const editor = this.editor
if (editor.cmd.queryCommandState('justifyCenter')) {
this.active()
} else {
this.unActive()
}
}
}
},{
key:"alignRight",
type:BtnMenu,
elem:`
`,
command:"justifyRight",
eventEnum:{
tryChangeActive:function(){
const editor = this.editor
if (editor.cmd.queryCommandState('justifyRight')) {
this.active()
} else {
this.unActive()
}
}
}
},{//文字颜色
key:"exFontColor",
type:DropListMenu,
elem:`
`,
exConfig:{
width: 100,
title: '文字颜色',
type: 'inline-block',
list: fontColorList.map(color => {
return {
$elem: $(` |