文件夹结构调整,新增模版自定义功能

This commit is contained in:
xiongxiaoyang
2020-12-26 19:13:07 +08:00
parent f03ab953d0
commit 6ad51908d5
601 changed files with 75656 additions and 8 deletions

View File

@ -0,0 +1,10 @@
{
"presets": [
["latest", {
"es2015": {
"modules": false
}
}]
],
"plugins": ["external-helpers"]
}

View File

@ -0,0 +1,106 @@
/*
命令,封装 document.execCommand
*/
import $ from '../util/dom-core.js'
import { UA } from '../util/util.js'
// 构造函数
function Command(editor) {
this.editor = editor
}
// 修改原型
Command.prototype = {
constructor: Command,
// 执行命令
do: function (name, value) {
const editor = this.editor
// 使用 styleWithCSS
if (!editor._useStyleWithCSS) {
document.execCommand('styleWithCSS', null, true)
editor._useStyleWithCSS = true
}
// 如果无选区,忽略
if (!editor.selection.getRange()) {
return
}
// 恢复选取
editor.selection.restoreSelection()
// 执行
const _name = '_' + name
if (this[_name]) {
// 有自定义事件
this[_name](value)
} else {
// 默认 command
this._execCommand(name, value)
}
// 修改菜单状态
editor.menus.changeActive()
// 最后,恢复选取保证光标在原来的位置闪烁
editor.selection.saveRange()
editor.selection.restoreSelection()
// 触发 onchange
editor.change && editor.change()
},
// 自定义 insertHTML 事件
_insertHTML: function (html) {
const editor = this.editor
const range = editor.selection.getRange()
if (this.queryCommandSupported('insertHTML')) {
// W3C
this._execCommand('insertHTML', html)
} else if (range.insertNode) {
// IE
range.deleteContents()
range.insertNode($(html)[0])
} else if (range.pasteHTML) {
// IE <= 10
range.pasteHTML(html)
}
},
// 插入 elem
_insertElem: function ($elem) {
const editor = this.editor
const range = editor.selection.getRange()
if (range.insertNode) {
range.deleteContents()
range.insertNode($elem[0])
}
},
// 封装 execCommand
_execCommand: function (name, value) {
document.execCommand(name, false, value)
},
// 封装 document.queryCommandValue
queryCommandValue: function (name) {
return document.queryCommandValue(name)
},
// 封装 document.queryCommandState
queryCommandState: function (name) {
return document.queryCommandState(name)
},
// 封装 document.queryCommandSupported
queryCommandSupported: function (name) {
return document.queryCommandSupported(name)
}
}
export default Command

View File

@ -0,0 +1,387 @@
/*
配置信息
*/
const config = {
// 默认菜单配置
menus: [
'head',
'bold',
'italic',
'underline',
'strikeThrough',
'foreColor',
'backColor',
'link',
'list',
'justify',
'quote',
'emoticon',
'image',
'table',
'video',
'code',
'undo',
'redo'
],
colors: [
'#000000',
'#eeece0',
'#1c487f',
'#4d80bf',
'#c24f4a',
'#8baa4a',
'#7b5ba1',
'#46acc8',
'#f9963b',
'#ffffff'
],
// // 语言配置
// lang: {
// '设置标题': 'title',
// '正文': 'p',
// '链接文字': 'link text',
// '链接': 'link',
// '插入': 'insert',
// '创建': 'init'
// },
// 表情
emotions: [
{
// tab 的标题
title: '默认',
// type -> 'emoji' / 'image'
type: 'image',
// content -> 数组
content: [
{
alt: '[坏笑]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/50/pcmoren_huaixiao_org.png'
},
{
alt: '[舔屏]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/40/pcmoren_tian_org.png'
},
{
alt: '[]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/3c/pcmoren_wu_org.png'
},
{
alt: '[允悲]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/2c/moren_yunbei_org.png'
},
{
alt: '[笑而不语]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/3a/moren_xiaoerbuyu_org.png'
},
{
alt: '[费解]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/3c/moren_feijie_org.png'
},
{
alt: '[憧憬]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/37/moren_chongjing_org.png'
},
{
alt: '[并不简单]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/fc/moren_bbjdnew_org.png'
},
{
alt: '[微笑]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/5c/huanglianwx_org.gif'
},
{
alt: '[]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/8a/pcmoren_cool2017_org.png'
},
{
alt: '[嘻嘻]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/0b/tootha_org.gif'
},
{
alt: '[哈哈]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/6a/laugh.gif'
},
{
alt: '[可爱]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/14/tza_org.gif'
},
{
alt: '[可怜]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/af/kl_org.gif'
},
{
alt: '[挖鼻]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/0b/wabi_org.gif'
},
{
alt: '[吃惊]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/f4/cj_org.gif'
},
{
alt: '[害羞]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/6e/shamea_org.gif'
},
{
alt: '[挤眼]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/c3/zy_org.gif'
},
{
alt: '[闭嘴]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/29/bz_org.gif'
},
{
alt: '[鄙视]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/71/bs2_org.gif'
},
{
alt: '[爱你]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/6d/lovea_org.gif'
},
{
alt: '[]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/9d/sada_org.gif'
},
{
alt: '[偷笑]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/19/heia_org.gif'
},
{
alt: '[亲亲]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/8f/qq_org.gif'
},
{
alt: '[生病]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/b6/sb_org.gif'
},
{
alt: '[太开心]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/58/mb_org.gif'
},
{
alt: '[白眼]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/d9/landeln_org.gif'
},
{
alt: '[右哼哼]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/98/yhh_org.gif'
},
{
alt: '[左哼哼]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/6d/zhh_org.gif'
},
{
alt: '[]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/a6/x_org.gif'
},
{
alt: '[]',
src: 'http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/af/cry.gif'
}
]
},
{
// tab 的标题
title: '新浪',
// type -> 'emoji' / 'image'
type: 'image',
// content -> 数组
content: [
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/7a/shenshou_thumb.gif',
alt: '[草泥马]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/60/horse2_thumb.gif',
alt: '[神马]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/bc/fuyun_thumb.gif',
alt: '[浮云]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/c9/geili_thumb.gif',
alt: '[给力]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/f2/wg_thumb.gif',
alt: '[围观]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/70/vw_thumb.gif',
alt: '[威武]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/6e/panda_thumb.gif',
alt: '[熊猫]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/81/rabbit_thumb.gif',
alt: '[兔子]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/bc/otm_thumb.gif',
alt: '[奥特曼]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/15/j_thumb.gif',
alt: '[]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/89/hufen_thumb.gif',
alt: '[互粉]'
},
{
src: 'http://img.t.sinajs.cn/t35/style/images/common/face/ext/normal/c4/liwu_thumb.gif',
alt: '[礼物]'
}
]
},
{
// tab 的标题
title: 'emoji',
// type -> 'emoji' / 'image'
type: 'emoji',
// content -> 数组
content: '😀 😃 😄 😁 😆 😅 😂 😊 😇 🙂 🙃 😉 😌 😍 😘 😗 😙 😚 😋 😜 😝 😛 🤑 🤗 🤓 😎 😏 😒 😞 😔 😟 😕 🙁 😣 😖 😫 😩 😤 😠 😡 😶 😐 😑 😯 😦 😧 😮 😲 😵 😳 😱 😨 😰 😢 😥 😭 😓 😪 😴 🙄 🤔 😬 🤐'.split(/\s/)
},
// {
// // tab 的标题
// title: '手势',
// // type -> 'emoji' / 'image'
// type: 'emoji',
// // content -> 数组
// content: ['🙌', '👏', '👋', '👍', '👎', '👊', '✊', '️👌', '✋', '👐', '💪', '🙏', '️👆', '👇', '👈', '👉', '🖕', '🖐', '🤘']
// }
],
// 编辑区域的 z-index
zIndex: 10000,
// 是否开启 debug 模式debug 模式下错误会 throw error 形式抛出)
debug: false,
// 插入链接时候的格式校验
linkCheck: function (text, link) {
// text 是插入的文字
// link 是插入的链接
return true // 返回 true 即表示成功
// return '校验失败' // 返回字符串即表示失败的提示信息
},
// 插入网络图片的校验
linkImgCheck: function (src) {
// src 即图片的地址
return true // 返回 true 即表示成功
// return '校验失败' // 返回字符串即表示失败的提示信息
},
// 粘贴过滤样式,默认开启
pasteFilterStyle: true,
// 对粘贴的文字进行自定义处理,返回处理后的结果。编辑器会将处理后的结果粘贴到编辑区域中。
// IE 暂时不支持
pasteTextHandle: function (content) {
// content 即粘贴过来的内容html 或 纯文本),可进行自定义处理然后返回
return content
},
// onchange 事件
// onchange: function (html) {
// // html 即变化之后的内容
// console.log(html)
// },
// 是否显示添加网络图片的 tab
showLinkImg: true,
// 插入网络图片的回调
linkImgCallback: function (url) {
// console.log(url) // url 即插入图片的地址
},
// 默认上传图片 max size: 5M
uploadImgMaxSize: 5 * 1024 * 1024,
// 配置一次最多上传几个图片
// uploadImgMaxLength: 5,
// 上传图片,是否显示 base64 格式
uploadImgShowBase64: false,
// 上传图片server 地址(如果有值,则 base64 格式的配置则失效)
// uploadImgServer: '/upload',
// 自定义配置 filename
uploadFileName: '',
// 上传图片的自定义参数
uploadImgParams: {
// token: 'abcdef12345'
},
// 上传图片的自定义header
uploadImgHeaders: {
// 'Accept': 'text/x-json'
},
// 配置 XHR withCredentials
withCredentials: false,
// 自定义上传图片超时时间 ms
uploadImgTimeout: 10000,
// 上传图片 hook
uploadImgHooks: {
// customInsert: function (insertLinkImg, result, editor) {
// console.log('customInsert')
// // 图片上传并返回结果,自定义插入图片的事件,而不是编辑器自动插入图片
// const data = result.data1 || []
// data.forEach(link => {
// insertLinkImg(link)
// })
// },
before: function (xhr, editor, files) {
// 图片上传之前触发
// 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
// return {
// prevent: true,
// msg: '放弃上传'
// }
},
success: function (xhr, editor, result) {
// 图片上传并返回结果,图片插入成功之后触发
},
fail: function (xhr, editor, result) {
// 图片上传并返回结果,但图片插入错误时触发
},
error: function (xhr, editor) {
// 图片上传出错时触发
},
timeout: function (xhr, editor) {
// 图片上传超时时触发
}
},
// 是否上传七牛云,默认为 false
qiniu: false,
// 上传图片自定义提示方法
// customAlert: function (info) {
// // 自定义上传提示
// },
// // 自定义上传图片
// customUploadImg: function (files, insert) {
// // files 是 input 中选中的文件列表
// // insert 是获取图片 url 后,插入到编辑器的方法
// insert(imgUrl)
// }
}
export default config

View File

@ -0,0 +1,339 @@
/*
编辑器构造函数
*/
import $ from '../util/dom-core.js'
import _config from '../config.js'
import Menus from '../menus/index.js'
import Text from '../text/index.js'
import Command from '../command/index.js'
import selectionAPI from '../selection/index.js'
import UploadImg from './upload/upload-img.js'
import { arrForEach, objForEach } from '../util/util.js'
import { getRandom } from '../util/util.js'
// id累加
let editorId = 1
// 构造函数
function Editor(toolbarSelector, textSelector) {
if (toolbarSelector == null) {
// 没有传入任何参数,报错
throw new Error('错误初始化编辑器时候未传入任何参数请查阅文档')
}
// id用以区分单个页面不同的编辑器对象
this.id = 'wangEditor-' + editorId++
this.toolbarSelector = toolbarSelector
this.textSelector = textSelector
// 自定义配置
this.customConfig = {}
}
// 修改原型
Editor.prototype = {
constructor: Editor,
// 初始化配置
_initConfig: function () {
// _config 是默认配置this.customConfig 是用户自定义配置,将它们 merge 之后再赋值
let target = {}
this.config = Object.assign(target, _config, this.customConfig)
// 将语言配置,生成正则表达式
const langConfig = this.config.lang || {}
const langArgs = []
objForEach(langConfig, (key, val) => {
// key 即需要生成正则表达式的规则,如“插入链接”
// val 即需要被替换成的语言如“insert link”
langArgs.push({
reg: new RegExp(key, 'img'),
val: val
})
})
this.config.langArgs = langArgs
},
// 初始化 DOM
_initDom: function () {
const toolbarSelector = this.toolbarSelector
const $toolbarSelector = $(toolbarSelector)
const textSelector = this.textSelector
const config = this.config
const zIndex = config.zIndex
// 定义变量
let $toolbarElem, $textContainerElem, $textElem, $children
if (textSelector == null) {
// 只传入一个参数即是容器的选择器或元素toolbar 和 text 的元素自行创建
$toolbarElem = $('<div></div>')
$textContainerElem = $('<div></div>')
// 将编辑器区域原有的内容,暂存起来
$children = $toolbarSelector.children()
// 添加到 DOM 结构中
$toolbarSelector.append($toolbarElem).append($textContainerElem)
// 自行创建的,需要配置默认的样式
$toolbarElem.css('background-color', '#f1f1f1')
.css('border', '1px solid #ccc')
$textContainerElem.css('border', '1px solid #ccc')
.css('border-top', 'none')
.css('height', '300px')
} else {
// toolbar 和 text 的选择器都有值,记录属性
$toolbarElem = $toolbarSelector
$textContainerElem = $(textSelector)
// 将编辑器区域原有的内容,暂存起来
$children = $textContainerElem.children()
}
// 编辑区域
$textElem = $('<div></div>')
$textElem.attr('contenteditable', 'true')
.css('width', '100%')
.css('height', '100%')
// 初始化编辑区域内容
if ($children && $children.length) {
$textElem.append($children)
} else {
$textElem.append($('<p><br></p>'))
}
// 编辑区域加入DOM
$textContainerElem.append($textElem)
// 设置通用的 class
$toolbarElem.addClass('w-e-toolbar')
$textContainerElem.addClass('w-e-text-container')
$textContainerElem.css('z-index', zIndex)
$textElem.addClass('w-e-text')
// 添加 ID
const toolbarElemId = getRandom('toolbar-elem')
$toolbarElem.attr('id', toolbarElemId)
const textElemId = getRandom('text-elem')
$textElem.attr('id', textElemId)
// 记录属性
this.$toolbarElem = $toolbarElem
this.$textContainerElem = $textContainerElem
this.$textElem = $textElem
this.toolbarElemId = toolbarElemId
this.textElemId = textElemId
// 记录输入法的开始和结束
let compositionEnd = true
$textContainerElem.on('compositionstart', () => {
// 输入法开始输入
compositionEnd = false
})
$textContainerElem.on('compositionend', () => {
// 输入法结束输入
compositionEnd = true
})
// 绑定 onchange
$textContainerElem.on('click keyup', () => {
// 输入法结束才出发 onchange
compositionEnd && this.change && this.change()
})
$toolbarElem.on('click', function () {
this.change && this.change()
})
//绑定 onfocus 与 onblur 事件
if(config.onfocus || config.onblur){
// 当前编辑器是否是焦点状态
this.isFocus = false
$(document).on('click', (e) => {
//判断当前点击元素是否在编辑器内
const isChild = $textElem.isContain($(e.target))
//判断当前点击元素是否为工具栏
const isToolbar = $toolbarElem.isContain($(e.target))
const isMenu = $toolbarElem[0] == e.target ? true : false
if (!isChild) {
//若为选择工具栏中的功能则不视为成blur操作
if(isToolbar && !isMenu){
return
}
if(this.isFocus){
this.onblur && this.onblur()
}
this.isFocus = false
}else{
if(!this.isFocus){
this.onfocus && this.onfocus()
}
this.isFocus = true
}
})
}
},
// 封装 command
_initCommand: function () {
this.cmd = new Command(this)
},
// 封装 selection range API
_initSelectionAPI: function () {
this.selection = new selectionAPI(this)
},
// 添加图片上传
_initUploadImg: function () {
this.uploadImg = new UploadImg(this)
},
// 初始化菜单
_initMenus: function () {
this.menus = new Menus(this)
this.menus.init()
},
// 添加 text 区域
_initText: function () {
this.txt = new Text(this)
this.txt.init()
},
// 初始化选区,将光标定位到内容尾部
initSelection: function (newLine) {
const $textElem = this.$textElem
const $children = $textElem.children()
if (!$children.length) {
// 如果编辑器区域无内容,添加一个空行,重新设置选区
$textElem.append($('<p><br></p>'))
this.initSelection()
return
}
const $last = $children.last()
if (newLine) {
// 新增一个空行
const html = $last.html().toLowerCase()
const nodeName = $last.getNodeName()
if ((html !== '<br>' && html !== '<br\/>') || nodeName !== 'P') {
// 最后一个元素不是 <p><br></p>,添加一个空行,重新设置选区
$textElem.append($('<p><br></p>'))
this.initSelection()
return
}
}
this.selection.createRangeByElem($last, false, true)
this.selection.restoreSelection()
},
// 绑定事件
_bindEvent: function () {
// -------- 绑定 onchange 事件 --------
let onChangeTimeoutId = 0
let beforeChangeHtml = this.txt.html()
const config = this.config
// onchange 触发延迟时间
let onchangeTimeout = config.onchangeTimeout
onchangeTimeout = parseInt(onchangeTimeout, 10)
if (!onchangeTimeout || onchangeTimeout <= 0) {
onchangeTimeout = 200
}
const onchange = config.onchange
if (onchange && typeof onchange === 'function'){
// 触发 change 的有三个场景:
// 1. $textContainerElem.on('click keyup')
// 2. $toolbarElem.on('click')
// 3. editor.cmd.do()
this.change = function () {
// 判断是否有变化
let currentHtml = this.txt.html()
if (currentHtml.length === beforeChangeHtml.length) {
// 需要比较每一个字符
if (currentHtml === beforeChangeHtml) {
return
}
}
// 执行,使用节流
if (onChangeTimeoutId) {
clearTimeout(onChangeTimeoutId)
}
onChangeTimeoutId = setTimeout(() => {
// 触发配置的 onchange 函数
onchange(currentHtml)
beforeChangeHtml = currentHtml
}, onchangeTimeout)
}
}
// -------- 绑定 onblur 事件 --------
const onblur = config.onblur
if (onblur && typeof onblur === 'function') {
this.onblur = function () {
const currentHtml = this.txt.html()
onblur(currentHtml)
}
}
// -------- 绑定 onfocus 事件 --------
const onfocus = config.onfocus
if (onfocus && typeof onfocus === 'function') {
this.onfocus = function () {
onfocus()
}
}
},
// 创建编辑器
create: function () {
// 初始化配置信息
this._initConfig()
// 初始化 DOM
this._initDom()
// 封装 command API
this._initCommand()
// 封装 selection range API
this._initSelectionAPI()
// 添加 text
this._initText()
// 初始化菜单
this._initMenus()
// 添加 图片上传
this._initUploadImg()
// 初始化选区,将光标定位到内容尾部
this.initSelection(true)
// 绑定事件
this._bindEvent()
},
// 解绑所有事件(暂时不对外开放)
_offAllEvent: function () {
$.offAll()
}
}
export default Editor

View File

@ -0,0 +1,65 @@
/*
上传进度条
*/
import $ from '../../util/dom-core.js'
function Progress(editor) {
this.editor = editor
this._time = 0
this._isShow = false
this._isRender = false
this._timeoutId = 0
this.$textContainer = editor.$textContainerElem
this.$bar = $('<div class="w-e-progress"></div>')
}
Progress.prototype = {
constructor: Progress,
show: function (progress) {
// 状态处理
if (this._isShow) {
return
}
this._isShow = true
// 渲染
const $bar = this.$bar
if (!this._isRender) {
const $textContainer = this.$textContainer
$textContainer.append($bar)
} else {
this._isRender = true
}
// 改变进度节流100ms 渲染一次)
if (Date.now() - this._time > 100) {
if (progress <= 1) {
$bar.css('width', progress * 100 + '%')
this._time = Date.now()
}
}
// 隐藏
let timeoutId = this._timeoutId
if (timeoutId) {
clearTimeout(timeoutId)
}
timeoutId = setTimeout(() => {
this._hide()
}, 500)
},
_hide: function () {
const $bar = this.$bar
$bar.remove()
// 修改状态
this._time = 0
this._isShow = false
this._isRender = false
}
}
export default Progress

View File

@ -0,0 +1,316 @@
/*
上传图片
*/
import { objForEach, arrForEach, percentFormat } from '../../util/util.js'
import Progress from './progress.js'
import { UA } from '../../util/util.js'
// 构造函数
function UploadImg(editor) {
this.editor = editor
}
// 原型
UploadImg.prototype = {
constructor: UploadImg,
// 根据 debug 弹出不同的信息
_alert: function (alertInfo, debugInfo) {
const editor = this.editor
const debug = editor.config.debug
const customAlert = editor.config.customAlert
if (debug) {
throw new Error('wangEditor: ' + (debugInfo || alertInfo))
} else {
if (customAlert && typeof customAlert === 'function') {
customAlert(alertInfo)
} else {
alert(alertInfo)
}
}
},
// 根据链接插入图片
insertLinkImg: function (link) {
if (!link) {
return
}
const editor = this.editor
const config = editor.config
// 校验格式
const linkImgCheck = config.linkImgCheck
let checkResult
if (linkImgCheck && typeof linkImgCheck === 'function') {
checkResult = linkImgCheck(link)
if (typeof checkResult === 'string') {
// 校验失败,提示信息
alert(checkResult)
return
}
}
editor.cmd.do('insertHTML', `<img src="${link}" style="max-width:100%;"/>`)
// 验证图片 url 是否有效,无效的话给出提示
let img = document.createElement('img')
img.onload = () => {
const callback = config.linkImgCallback
if (callback && typeof callback === 'function') {
callback(link)
}
img = null
}
img.onerror = () => {
img = null
// 无法成功下载图片
this._alert('插入图片错误', `wangEditor: 插入图片出错图片链接是 "${link}"下载该链接失败`)
return
}
img.onabort = () => {
img = null
}
img.src = link
},
// 上传图片
uploadImg: function (files) {
if (!files || !files.length) {
return
}
// ------------------------------ 获取配置信息 ------------------------------
const editor = this.editor
const config = editor.config
let uploadImgServer = config.uploadImgServer
const uploadImgShowBase64 = config.uploadImgShowBase64
const maxSize = config.uploadImgMaxSize
const maxSizeM = maxSize / 1024 / 1024
const maxLength = config.uploadImgMaxLength || 10000
const uploadFileName = config.uploadFileName || ''
const uploadImgParams = config.uploadImgParams || {}
const uploadImgParamsWithUrl = config.uploadImgParamsWithUrl
const uploadImgHeaders = config.uploadImgHeaders || {}
const hooks = config.uploadImgHooks || {}
const timeout = config.uploadImgTimeout || 3000
let withCredentials = config.withCredentials
if (withCredentials == null) {
withCredentials = false
}
const customUploadImg = config.customUploadImg
if (!customUploadImg) {
// 没有 customUploadImg 的情况下,需要如下两个配置才能继续进行图片上传
if (!uploadImgServer && !uploadImgShowBase64) {
return
}
}
// ------------------------------ 验证文件信息 ------------------------------
const resultFiles = []
let errInfo = []
arrForEach(files, file => {
var name = file.name
var size = file.size
// chrome 低版本 name === undefined
if (!name || !size) {
return
}
if (/\.(jpg|jpeg|png|bmp|gif)$/i.test(name) === false) {
// 后缀名不合法,不是图片
errInfo.push(`${name}不是图片`)
return
}
if (maxSize < size) {
// 上传图片过大
errInfo.push(`${name}大于 ${maxSizeM}M`)
return
}
// 验证通过的加入结果列表
resultFiles.push(file)
})
// 抛出验证信息
if (errInfo.length) {
this._alert('图片验证未通过: \n' + errInfo.join('\n'))
return
}
if (resultFiles.length > maxLength) {
this._alert('一次最多上传' + maxLength + '张图片')
return
}
// ------------------------------ 自定义上传 ------------------------------
if (customUploadImg && typeof customUploadImg === 'function') {
customUploadImg(resultFiles, this.insertLinkImg.bind(this))
// 阻止以下代码执行
return
}
// 添加图片数据
const formdata = new FormData()
arrForEach(resultFiles, file => {
const name = uploadFileName || file.name
formdata.append(name, file)
})
// ------------------------------ 上传图片 ------------------------------
if (uploadImgServer && typeof uploadImgServer === 'string') {
// 添加参数
const uploadImgServerArr = uploadImgServer.split('#')
uploadImgServer = uploadImgServerArr[0]
const uploadImgServerHash = uploadImgServerArr[1] || ''
objForEach(uploadImgParams, (key, val) => {
val = encodeURIComponent(val)
// 第一,将参数拼接到 url 中
if (uploadImgParamsWithUrl) {
if (uploadImgServer.indexOf('?') > 0) {
uploadImgServer += '&'
} else {
uploadImgServer += '?'
}
uploadImgServer = uploadImgServer + key + '=' + val
}
// 第二,将参数添加到 formdata 中
formdata.append(key, val)
})
if (uploadImgServerHash) {
uploadImgServer += '#' + uploadImgServerHash
}
// 定义 xhr
const xhr = new XMLHttpRequest()
xhr.open('POST', uploadImgServer)
// 设置超时
xhr.timeout = timeout
xhr.ontimeout = () => {
// hook - timeout
if (hooks.timeout && typeof hooks.timeout === 'function') {
hooks.timeout(xhr, editor)
}
this._alert('上传图片超时')
}
// 监控 progress
if (xhr.upload) {
xhr.upload.onprogress = e => {
let percent
// 进度条
const progressBar = new Progress(editor)
if (e.lengthComputable) {
percent = e.loaded / e.total
progressBar.show(percent)
}
}
}
// 返回数据
xhr.onreadystatechange = () => {
let result
if (xhr.readyState === 4) {
if (xhr.status < 200 || xhr.status >= 300) {
// hook - error
if (hooks.error && typeof hooks.error === 'function') {
hooks.error(xhr, editor)
}
// xhr 返回状态错误
this._alert('上传图片发生错误', `上传图片发生错误服务器返回状态是 ${xhr.status}`)
return
}
result = xhr.responseText
if (typeof result !== 'object') {
try {
result = JSON.parse(result)
} catch (ex) {
// hook - fail
if (hooks.fail && typeof hooks.fail === 'function') {
hooks.fail(xhr, editor, result)
}
this._alert('上传图片失败', '上传图片返回结果错误返回结果是: ' + result)
return
}
}
if (!hooks.customInsert && result.errno != '0') {
// hook - fail
if (hooks.fail && typeof hooks.fail === 'function') {
hooks.fail(xhr, editor, result)
}
// 数据错误
this._alert('上传图片失败', '上传图片返回结果错误返回结果 errno=' + result.errno)
} else {
if (hooks.customInsert && typeof hooks.customInsert === 'function') {
// 使用者自定义插入方法
hooks.customInsert(this.insertLinkImg.bind(this), result, editor)
} else {
// 将图片插入编辑器
const data = result.data || []
data.forEach(link => {
this.insertLinkImg(link)
})
}
// hook - success
if (hooks.success && typeof hooks.success === 'function') {
hooks.success(xhr, editor, result)
}
}
}
}
// hook - before
if (hooks.before && typeof hooks.before === 'function') {
const beforeResult = hooks.before(xhr, editor, resultFiles)
if (beforeResult && typeof beforeResult === 'object') {
if (beforeResult.prevent) {
// 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
this._alert(beforeResult.msg)
return
}
}
}
// 自定义 headers
objForEach(uploadImgHeaders, (key, val) => {
xhr.setRequestHeader(key, val)
})
// 跨域传 cookie
xhr.withCredentials = withCredentials
// 发送请求
xhr.send(formdata)
// 注意,要 return 。不去操作接下来的 base64 显示方式
return
}
// ------------------------------ 显示 base64 格式 ------------------------------
if (uploadImgShowBase64) {
arrForEach(files, file => {
const _this = this
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function () {
_this.insertLinkImg(this.result)
}
})
}
}
}
export default UploadImg

View File

@ -0,0 +1,24 @@
import polyfill from './util/poly-fill.js'
import Editor from './editor/index.js'
// 检验是否浏览器环境
try {
document
} catch (ex) {
throw new Error('请在浏览器环境下运行')
}
// polyfill
polyfill()
// 这里的 `inlinecss` 将被替换成 css 代码的内容,详情可去 ./gulpfile.js 中搜索 `inlinecss` 关键字
const inlinecss = '__INLINE_CSS__'
// 将 css 代码添加到 <style> 中
let style = document.createElement('style')
style.type = 'text/css'
style.innerHTML= inlinecss
document.getElementsByTagName('HEAD').item(0).appendChild(style)
// 返回
export default (window.wangEditor || Editor)

View File

@ -0,0 +1,46 @@
/*
menu - BackColor
*/
import $ from '../../util/dom-core.js'
import DropList from '../droplist.js'
// 构造函数
function BackColor(editor) {
this.editor = editor
this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-paint-brush"><i/></div>')
this.type = 'droplist'
// 获取配置的颜色
const config = editor.config
const colors = config.colors || []
// 当前是否 active 状态
this._active = false
// 初始化 droplist
this.droplist = new DropList(this, {
width: 120,
$title: $('<p>背景色</p>'),
type: 'inline-block', // droplist 内容以 block 形式展示
list: colors.map(color => {
return { $elem: $(`<i style="color:${color};" class="w-e-icon-paint-brush"></i>`), value: color }
}),
onClick: (value) => {
// 注意 this 是指向当前的 BackColor 对象
this._command(value)
}
})
}
// 原型
BackColor.prototype = {
constructor: BackColor,
// 执行命令
_command: function (value) {
const editor = this.editor
editor.cmd.do('backColor', value)
}
}
export default BackColor

View File

@ -0,0 +1,60 @@
/*
bold-menu
*/
import $ from '../../util/dom-core.js'
// 构造函数
function Bold(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-bold"><i/>
</div>`
)
this.type = 'click'
// 当前是否 active 状态
this._active = false
}
// 原型
Bold.prototype = {
constructor: Bold,
// 点击事件
onClick: function (e) {
// 点击菜单将触发这里
const editor = this.editor
const isSeleEmpty = editor.selection.isSelectionEmpty()
if (isSeleEmpty) {
// 选区是空的,插入并选中一个“空白”
editor.selection.createEmptyRange()
}
// 执行 bold 命令
editor.cmd.do('bold')
if (isSeleEmpty) {
// 需要将选取折叠起来
editor.selection.collapseRange()
editor.selection.restoreSelection()
}
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
if (editor.cmd.queryCommandState('bold')) {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Bold

View File

@ -0,0 +1,150 @@
/*
menu - code
*/
import $ from '../../util/dom-core.js'
import { getRandom, replaceHtmlSymbol } from '../../util/util.js'
import Panel from '../panel.js'
import { UA } from '../../util/util.js'
// 构造函数
function Code(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-terminal"><i/>
</div>`
)
this.type = 'panel'
// 当前是否 active 状态
this._active = false
}
// 原型
Code.prototype = {
constructor: Code,
onClick: function (e) {
const editor = this.editor
const $startElem = editor.selection.getSelectionStartElem()
const $endElem = editor.selection.getSelectionEndElem()
const isSeleEmpty = editor.selection.isSelectionEmpty()
const selectionText = editor.selection.getSelectionText()
let $code
if (!$startElem.equal($endElem)) {
// 跨元素选择,不做处理
editor.selection.restoreSelection()
return
}
if (!isSeleEmpty) {
// 选取不是空,用 <code> 包裹即可
$code = $(`<code>${selectionText}</code>`)
editor.cmd.do('insertElem', $code)
editor.selection.createRangeByElem($code, false)
editor.selection.restoreSelection()
return
}
// 选取是空,且没有夸元素选择,则插入 <pre><code></code></prev>
if (this._active) {
// 选中状态,将编辑内容
this._createPanel($startElem.html())
} else {
// 未选中状态,将创建内容
this._createPanel()
}
},
_createPanel: function (value) {
// value - 要编辑的内容
value = value || ''
const type = !value ? 'new' : 'edit'
const textId = getRandom('texxt')
const btnId = getRandom('btn')
const panel = new Panel(this, {
width: 500,
// 一个 Panel 包含多个 tab
tabs: [
{
// 标题
title: '插入代码',
// 模板
tpl: `<div>
<textarea id="${textId}" style="height:145px;;">${value}</textarea>
<div class="w-e-button-container">
<button id="${btnId}" class="right">插入</button>
</div>
<div>`,
// 事件绑定
events: [
// 插入代码
{
selector: '#' + btnId,
type: 'click',
fn: () => {
const $text = $('#' + textId)
let text = $text.val() || $text.html()
text = replaceHtmlSymbol(text)
if (type === 'new') {
// 新插入
this._insertCode(text)
} else {
// 编辑更新
this._updateCode(text)
}
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
}
]
} // first tab end
] // tabs end
}) // new Panel end
// 显示 panel
panel.show()
// 记录属性
this.panel = panel
},
// 插入代码
_insertCode: function (value) {
const editor = this.editor
editor.cmd.do('insertHTML', `<pre><code>${value}</code></pre><p><br></p>`)
},
// 更新代码
_updateCode: function (value) {
const editor = this.editor
const $selectionELem = editor.selection.getSelectionContainerElem()
if (!$selectionELem) {
return
}
$selectionELem.html(value)
editor.selection.restoreSelection()
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
const $selectionELem = editor.selection.getSelectionContainerElem()
if (!$selectionELem) {
return
}
const $parentElem = $selectionELem.parent()
if ($selectionELem.getNodeName() === 'CODE' && $parentElem.getNodeName() === 'PRE') {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Code

View File

@ -0,0 +1,130 @@
/*
droplist
*/
import $ from '../util/dom-core.js'
import replaceLang from '../util/replace-lang.js'
const _emptyFn = () => {}
// 构造函数
function DropList(menu, opt) {
// droplist 所依附的菜单
const editor = menu.editor
this.menu = menu
this.opt = opt
// 容器
const $container = $('<div class="w-e-droplist"></div>')
// 标题
const $title = opt.$title
let titleHtml
if ($title) {
// 替换多语言
titleHtml = $title.html()
titleHtml = replaceLang(editor, titleHtml)
$title.html(titleHtml)
$title.addClass('w-e-dp-title')
$container.append($title)
}
const list = opt.list || []
const type = opt.type || 'list' // 'list' 列表形式(如“标题”菜单) / 'inline-block' 块状形式(如“颜色”菜单)
const onClick = opt.onClick || _emptyFn
// 加入 DOM 并绑定事件
const $list = $('<ul class="' + (type === 'list' ? 'w-e-list' : 'w-e-block') + '"></ul>')
$container.append($list)
list.forEach(item => {
const $elem = item.$elem
// 替换多语言
let elemHtml = $elem.html()
elemHtml = replaceLang(editor, elemHtml)
$elem.html(elemHtml)
const value = item.value
const $li = $('<li class="w-e-item"></li>')
if ($elem) {
$li.append($elem)
$list.append($li)
$li.on('click', e => {
onClick(value)
// 隐藏
this.hideTimeoutId = setTimeout(() => {
this.hide()
}, 0)
})
}
})
// 绑定隐藏事件
$container.on('mouseleave', e => {
this.hideTimeoutId = setTimeout(() => {
this.hide()
}, 0)
})
// 记录属性
this.$container = $container
// 基本属性
this._rendered = false
this._show = false
}
// 原型
DropList.prototype = {
constructor: DropList,
// 显示插入DOM
show: function () {
if (this.hideTimeoutId) {
// 清除之前的定时隐藏
clearTimeout(this.hideTimeoutId)
}
const menu = this.menu
const $menuELem = menu.$elem
const $container = this.$container
if (this._show) {
return
}
if (this._rendered) {
// 显示
$container.show()
} else {
// 加入 DOM 之前先定位位置
const menuHeight = $menuELem.getSizeData().height || 0
const width = this.opt.width || 100 // 默认为 100
$container.css('margin-top', menuHeight + 'px')
.css('width', width + 'px')
// 加入到 DOM
$menuELem.append($container)
this._rendered = true
}
// 修改属性
this._show = true
},
// 隐藏移除DOM
hide: function () {
if (this.showTimeoutId) {
// 清除之前的定时显示
clearTimeout(this.showTimeoutId)
}
const $container = this.$container
if (!this._show) {
return
}
// 隐藏并需改属性
$container.hide()
this._show = false
}
}
export default DropList

View File

@ -0,0 +1,115 @@
/*
menu - emoticon
*/
import $ from '../../util/dom-core.js'
import Panel from '../panel.js'
// 构造函数
function Emoticon(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-happy"><i/>
</div>`
)
this.type = 'panel'
// 当前是否 active 状态
this._active = false
}
// 原型
Emoticon.prototype = {
constructor: Emoticon,
onClick: function () {
this._createPanel()
},
_createPanel: function () {
const editor = this.editor
const config = editor.config
// 获取表情配置
const emotions = config.emotions || []
// 创建表情 dropPanel 的配置
const tabConfig = []
emotions.forEach(emotData => {
const emotType = emotData.type
const content = emotData.content || []
// 这一组表情最终拼接出来的 html
let faceHtml = ''
// emoji 表情
if (emotType === 'emoji') {
content.forEach(item => {
if (item) {
faceHtml += '<span class="w-e-item">' + item + '</span>'
}
})
}
// 图片表情
if (emotType === 'image') {
content.forEach(item => {
const src = item.src
const alt = item.alt
if (src) {
// 加一个 data-w-e 属性,点击图片的时候不再提示编辑图片
faceHtml += '<span class="w-e-item"><img src="' + src + '" alt="' + alt + '" data-w-e="1"/></span>'
}
})
}
tabConfig.push({
title: emotData.title,
tpl: `<div class="w-e-emoticon-container">${faceHtml}</div>`,
events: [
{
selector: 'span.w-e-item',
type: 'click',
fn: (e) => {
const target = e.target
const $target = $(target)
const nodeName = $target.getNodeName()
let insertHtml
if (nodeName === 'IMG') {
// 插入图片
insertHtml = $target.parent().html()
} else {
// 插入 emoji
insertHtml = '<span>' + $target.html() + '</span>'
}
this._insert(insertHtml)
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
}
]
})
})
const panel = new Panel(this, {
width: 300,
height: 200,
// 一个 Panel 包含多个 tab
tabs: tabConfig
})
// 显示 panel
panel.show()
// 记录属性
this.panel = panel
},
// 插入表情
_insert: function (emotHtml) {
const editor = this.editor
editor.cmd.do('insertHTML', emotHtml)
}
}
export default Emoticon

View File

@ -0,0 +1,46 @@
/*
menu - Forecolor
*/
import $ from '../../util/dom-core.js'
import DropList from '../droplist.js'
// 构造函数
function ForeColor(editor) {
this.editor = editor
this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-pencil2"><i/></div>')
this.type = 'droplist'
// 获取配置的颜色
const config = editor.config
const colors = config.colors || []
// 当前是否 active 状态
this._active = false
// 初始化 droplist
this.droplist = new DropList(this, {
width: 120,
$title: $('<p>文字颜色</p>'),
type: 'inline-block', // droplist 内容以 block 形式展示
list: colors.map(color => {
return { $elem: $(`<i style="color:${color};" class="w-e-icon-pencil2"></i>`), value: color }
}),
onClick: (value) => {
// 注意 this 是指向当前的 ForeColor 对象
this._command(value)
}
})
}
// 原型
ForeColor.prototype = {
constructor: ForeColor,
// 执行命令
_command: function (value) {
const editor = this.editor
editor.cmd.do('foreColor', value)
}
}
export default ForeColor

View File

@ -0,0 +1,70 @@
/*
menu - header
*/
import $ from '../../util/dom-core.js'
import DropList from '../droplist.js'
// 构造函数
function Head(editor) {
this.editor = editor
this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-header"><i/></div>')
this.type = 'droplist'
// 当前是否 active 状态
this._active = false
// 初始化 droplist
this.droplist = new DropList(this, {
width: 100,
$title: $('<p>设置标题</p>'),
type: 'list', // droplist 以列表形式展示
list: [
{ $elem: $('<h1>H1</h1>'), value: '<h1>' },
{ $elem: $('<h2>H2</h2>'), value: '<h2>' },
{ $elem: $('<h3>H3</h3>'), value: '<h3>' },
{ $elem: $('<h4>H4</h4>'), value: '<h4>' },
{ $elem: $('<h5>H5</h5>'), value: '<h5>' },
{ $elem: $('<p>正文</p>'), value: '<p>' }
],
onClick: (value) => {
// 注意 this 是指向当前的 Head 对象
this._command(value)
}
})
}
// 原型
Head.prototype = {
constructor: Head,
// 执行命令
_command: function (value) {
const editor = this.editor
const $selectionElem = editor.selection.getSelectionContainerElem()
if (editor.$textElem.equal($selectionElem)) {
// 不能选中多行来设置标题,否则会出现问题
// 例如选中的是 <p>xxx</p><p>yyy</p> 来设置标题,设置之后会成为 <h1>xxx<br>yyy</h1> 不符合预期
return
}
editor.cmd.do('formatBlock', value)
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
const reg = /^h/i
const cmdValue = editor.cmd.queryCommandValue('formatBlock')
if (reg.test(cmdValue)) {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Head

View File

@ -0,0 +1,252 @@
/*
menu - img
*/
import $ from '../../util/dom-core.js'
import { getRandom, arrForEach } from '../../util/util.js'
import Panel from '../panel.js'
// 构造函数
function Image(editor) {
this.editor = editor
const imgMenuId = getRandom('w-e-img')
this.$elem = $('<div class="w-e-menu" id="' + imgMenuId + '"><i class="w-e-icon-image"><i/></div>')
editor.imgMenuId = imgMenuId
this.type = 'panel'
// 当前是否 active 状态
this._active = false
}
// 原型
Image.prototype = {
constructor: Image,
onClick: function () {
const editor = this.editor
const config = editor.config
if (config.qiniu) {
return
}
if (this._active) {
this._createEditPanel()
} else {
this._createInsertPanel()
}
},
_createEditPanel: function () {
const editor = this.editor
// id
const width30 = getRandom('width-30')
const width50 = getRandom('width-50')
const width100 = getRandom('width-100')
const delBtn = getRandom('del-btn')
// tab 配置
const tabsConfig = [
{
title: '编辑图片',
tpl: `<div>
<div class="w-e-button-container" style="border-bottom:1px solid #f1f1f1;padding-bottom:5px;margin-bottom:5px;">
<span style="float:left;font-size:14px;margin:4px 5px 0 5px;color:#333;">最大宽度:</span>
<button id="${width30}" class="left">30%</button>
<button id="${width50}" class="left">50%</button>
<button id="${width100}" class="left">100%</button>
</div>
<div class="w-e-button-container">
<button id="${delBtn}" class="gray left">删除图片</button>
</dv>
</div>`,
events: [
{
selector: '#' + width30,
type: 'click',
fn: () => {
const $img = editor._selectedImg
if ($img) {
$img.css('max-width', '30%')
}
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
},
{
selector: '#' + width50,
type: 'click',
fn: () => {
const $img = editor._selectedImg
if ($img) {
$img.css('max-width', '50%')
}
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
},
{
selector: '#' + width100,
type: 'click',
fn: () => {
const $img = editor._selectedImg
if ($img) {
$img.css('max-width', '100%')
}
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
},
{
selector: '#' + delBtn,
type: 'click',
fn: () => {
const $img = editor._selectedImg
if ($img) {
$img.remove()
}
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
}
]
}
]
// 创建 panel 并显示
const panel = new Panel(this, {
width: 300,
tabs: tabsConfig
})
panel.show()
// 记录属性
this.panel = panel
},
_createInsertPanel: function () {
const editor = this.editor
const uploadImg = editor.uploadImg
const config = editor.config
// id
const upTriggerId = getRandom('up-trigger')
const upFileId = getRandom('up-file')
const linkUrlId = getRandom('link-url')
const linkBtnId = getRandom('link-btn')
// tabs 的配置
const tabsConfig = [
{
title: '上传图片',
tpl: `<div class="w-e-up-img-container">
<div id="${upTriggerId}" class="w-e-up-btn">
<i class="w-e-icon-upload2"></i>
</div>
<div style="display:none;">
<input id="${upFileId}" type="file" multiple="multiple" accept="image/jpg,image/jpeg,image/png,image/gif,image/bmp"/>
</div>
</div>`,
events: [
{
// 触发选择图片
selector: '#' + upTriggerId,
type: 'click',
fn: () => {
const $file = $('#' + upFileId)
const fileElem = $file[0]
if (fileElem) {
fileElem.click()
} else {
// 返回 true 可关闭 panel
return true
}
}
},
{
// 选择图片完毕
selector: '#' + upFileId,
type: 'change',
fn: () => {
const $file = $('#' + upFileId)
const fileElem = $file[0]
if (!fileElem) {
// 返回 true 可关闭 panel
return true
}
// 获取选中的 file 对象列表
const fileList = fileElem.files
if (fileList.length) {
uploadImg.uploadImg(fileList)
}
// 返回 true 可关闭 panel
return true
}
}
]
}, // first tab end
{
title: '网络图片',
tpl: `<div>
<input id="${linkUrlId}" type="text" class="block" placeholder="图片链接"/></td>
<div class="w-e-button-container">
<button id="${linkBtnId}" class="right">插入</button>
</div>
</div>`,
events: [
{
selector: '#' + linkBtnId,
type: 'click',
fn: () => {
const $linkUrl = $('#' + linkUrlId)
const url = $linkUrl.val().trim()
if (url) {
uploadImg.insertLinkImg(url)
}
// 返回 true 表示函数执行结束之后关闭 panel
return true
}
}
]
} // second tab end
] // tabs end
// 判断 tabs 的显示
const tabsConfigResult = []
if ((config.uploadImgShowBase64 || config.uploadImgServer || config.customUploadImg) && window.FileReader) {
// 显示“上传图片”
tabsConfigResult.push(tabsConfig[0])
}
if (config.showLinkImg) {
// 显示“网络图片”
tabsConfigResult.push(tabsConfig[1])
}
// 创建 panel 并显示
const panel = new Panel(this, {
width: 300,
tabs: tabsConfigResult
})
panel.show()
// 记录属性
this.panel = panel
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
if (editor._selectedImg) {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Image

View File

@ -0,0 +1,125 @@
/*
菜单集合
*/
import { objForEach } from '../util/util.js'
import MenuConstructors from './menu-list.js'
// 构造函数
function Menus(editor) {
this.editor = editor
this.menus = {}
}
// 修改原型
Menus.prototype = {
constructor: Menus,
// 初始化菜单
init: function () {
const editor = this.editor
const config = editor.config || {}
const configMenus = config.menus || [] // 获取配置中的菜单
// 根据配置信息,创建菜单
configMenus.forEach(menuKey => {
const MenuConstructor = MenuConstructors[menuKey]
if (MenuConstructor && typeof MenuConstructor === 'function') {
// 创建单个菜单
this.menus[menuKey] = new MenuConstructor(editor)
}
})
// 添加到菜单栏
this._addToToolbar()
// 绑定事件
this._bindEvent()
},
// 添加到菜单栏
_addToToolbar: function () {
const editor = this.editor
const $toolbarElem = editor.$toolbarElem
const menus = this.menus
const config = editor.config
// config.zIndex 是配置的编辑区域的 z-index菜单的 z-index 得在其基础上 +1
const zIndex = config.zIndex + 1
objForEach(menus, (key, menu) => {
const $elem = menu.$elem
if ($elem) {
// 设置 z-index
$elem.css('z-index', zIndex)
$toolbarElem.append($elem)
}
})
},
// 绑定菜单 click mouseenter 事件
_bindEvent: function () {
const menus = this.menus
const editor = this.editor
objForEach(menus, (key, menu) => {
const type = menu.type
if (!type) {
return
}
const $elem = menu.$elem
const droplist = menu.droplist
const panel = menu.panel
// 点击类型,例如 bold
if (type === 'click' && menu.onClick) {
$elem.on('click', e => {
if (editor.selection.getRange() == null) {
return
}
menu.onClick(e)
})
}
// 下拉框,例如 head
if (type === 'droplist' && droplist) {
$elem.on('mouseenter', e => {
if (editor.selection.getRange() == null) {
return
}
// 显示
droplist.showTimeoutId = setTimeout(() => {
droplist.show()
}, 200)
}).on('mouseleave', e => {
// 隐藏
droplist.hideTimeoutId = setTimeout(() => {
droplist.hide()
}, 0)
})
}
// 弹框类型,例如 link
if (type === 'panel' && menu.onClick) {
$elem.on('click', e => {
e.stopPropagation()
if (editor.selection.getRange() == null) {
return
}
// 在自定义事件中显示 panel
menu.onClick(e)
})
}
})
},
// 尝试修改菜单状态
changeActive: function () {
const menus = this.menus
objForEach(menus, (key, menu) => {
if (menu.tryChangeActive) {
setTimeout(() => {
menu.tryChangeActive()
}, 100)
}
})
}
}
export default Menus

View File

@ -0,0 +1,60 @@
/*
italic-menu
*/
import $ from '../../util/dom-core.js'
// 构造函数
function Italic(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-italic"><i/>
</div>`
)
this.type = 'click'
// 当前是否 active 状态
this._active = false
}
// 原型
Italic.prototype = {
constructor: Italic,
// 点击事件
onClick: function (e) {
// 点击菜单将触发这里
const editor = this.editor
const isSeleEmpty = editor.selection.isSelectionEmpty()
if (isSeleEmpty) {
// 选区是空的,插入并选中一个“空白”
editor.selection.createEmptyRange()
}
// 执行 italic 命令
editor.cmd.do('italic')
if (isSeleEmpty) {
// 需要将选取折叠起来
editor.selection.collapseRange()
editor.selection.restoreSelection()
}
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
if (editor.cmd.queryCommandState('italic')) {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Italic

View File

@ -0,0 +1,44 @@
/*
menu - justify
*/
import $ from '../../util/dom-core.js'
import DropList from '../droplist.js'
// 构造函数
function Justify(editor) {
this.editor = editor
this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-paragraph-left"><i/></div>')
this.type = 'droplist'
// 当前是否 active 状态
this._active = false
// 初始化 droplist
this.droplist = new DropList(this, {
width: 100,
$title: $('<p>对齐方式</p>'),
type: 'list', // droplist 以列表形式展示
list: [
{ $elem: $('<span><i class="w-e-icon-paragraph-left"></i> 靠左</span>'), value: 'justifyLeft' },
{ $elem: $('<span><i class="w-e-icon-paragraph-center"></i> 居中</span>'), value: 'justifyCenter' },
{ $elem: $('<span><i class="w-e-icon-paragraph-right"></i> 靠右</span>'), value: 'justifyRight' }
],
onClick: (value) => {
// 注意 this 是指向当前的 List 对象
this._command(value)
}
})
}
// 原型
Justify.prototype = {
constructor: Justify,
// 执行命令
_command: function (value) {
const editor = this.editor
editor.cmd.do(value)
}
}
export default Justify

View File

@ -0,0 +1,168 @@
/*
menu - link
*/
import $ from '../../util/dom-core.js'
import { getRandom } from '../../util/util.js'
import Panel from '../panel.js'
// 构造函数
function Link(editor) {
this.editor = editor
this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-link"><i/></div>')
this.type = 'panel'
// 当前是否 active 状态
this._active = false
}
// 原型
Link.prototype = {
constructor: Link,
// 点击事件
onClick: function (e) {
const editor = this.editor
let $linkelem
if (this._active) {
// 当前选区在链接里面
$linkelem = editor.selection.getSelectionContainerElem()
if (!$linkelem) {
return
}
// 将该元素都包含在选取之内,以便后面整体替换
editor.selection.createRangeByElem($linkelem)
editor.selection.restoreSelection()
// 显示 panel
this._createPanel($linkelem.text(), $linkelem.attr('href'))
} else {
// 当前选区不在链接里面
if (editor.selection.isSelectionEmpty()) {
// 选区是空的,未选中内容
this._createPanel('', '')
} else {
// 选中内容了
this._createPanel(editor.selection.getSelectionText(), '')
}
}
},
// 创建 panel
_createPanel: function (text, link) {
// panel 中需要用到的id
const inputLinkId = getRandom('input-link')
const inputTextId = getRandom('input-text')
const btnOkId = getRandom('btn-ok')
const btnDelId = getRandom('btn-del')
// 是否显示“删除链接”
const delBtnDisplay = this._active ? 'inline-block' : 'none'
// 初始化并显示 panel
const panel = new Panel(this, {
width: 300,
// panel 中可包含多个 tab
tabs: [
{
// tab 的标题
title: '链接',
// 模板
tpl: `<div>
<input id="${inputTextId}" type="text" class="block" value="${text}" placeholder="链接文字"/></td>
<input id="${inputLinkId}" type="text" class="block" value="${link}" placeholder="http://..."/></td>
<div class="w-e-button-container">
<button id="${btnOkId}" class="right">插入</button>
<button id="${btnDelId}" class="gray right" style="display:${delBtnDisplay}">删除链接</button>
</div>
</div>`,
// 事件绑定
events: [
// 插入链接
{
selector: '#' + btnOkId,
type: 'click',
fn: () => {
// 执行插入链接
const $link = $('#' + inputLinkId)
const $text = $('#' + inputTextId)
const link = $link.val()
const text = $text.val()
this._insertLink(text, link)
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
},
// 删除链接
{
selector: '#' + btnDelId,
type: 'click',
fn: () => {
// 执行删除链接
this._delLink()
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
}
]
} // tab end
] // tabs end
})
// 显示 panel
panel.show()
// 记录属性
this.panel = panel
},
// 删除当前链接
_delLink: function () {
if (!this._active) {
return
}
const editor = this.editor
const $selectionELem = editor.selection.getSelectionContainerElem()
if (!$selectionELem) {
return
}
const selectionText = editor.selection.getSelectionText()
editor.cmd.do('insertHTML', '<span>' + selectionText + '</span>')
},
// 插入链接
_insertLink: function (text, link) {
const editor = this.editor
const config = editor.config
const linkCheck = config.linkCheck
let checkResult = true // 默认为 true
if (linkCheck && typeof linkCheck === 'function') {
checkResult = linkCheck(text, link)
}
if (checkResult === true) {
editor.cmd.do('insertHTML', `<a href="${link}" target="_blank">${text}</a>`)
} else {
alert(checkResult)
}
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
const $selectionELem = editor.selection.getSelectionContainerElem()
if (!$selectionELem) {
return
}
if ($selectionELem.getNodeName() === 'A') {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Link

View File

@ -0,0 +1,82 @@
/*
menu - list
*/
import $ from '../../util/dom-core.js'
import DropList from '../droplist.js'
// 构造函数
function List(editor) {
this.editor = editor
this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-list2"><i/></div>')
this.type = 'droplist'
// 当前是否 active 状态
this._active = false
// 初始化 droplist
this.droplist = new DropList(this, {
width: 120,
$title: $('<p>设置列表</p>'),
type: 'list', // droplist 以列表形式展示
list: [
{ $elem: $('<span><i class="w-e-icon-list-numbered"></i> 有序列表</span>'), value: 'insertOrderedList' },
{ $elem: $('<span><i class="w-e-icon-list2"></i> 无序列表</span>'), value: 'insertUnorderedList' }
],
onClick: (value) => {
// 注意 this 是指向当前的 List 对象
this._command(value)
}
})
}
// 原型
List.prototype = {
constructor: List,
// 执行命令
_command: function (value) {
const editor = this.editor
const $textElem = editor.$textElem
editor.selection.restoreSelection()
if (editor.cmd.queryCommandState(value)) {
return
}
editor.cmd.do(value)
// 验证列表是否被包裹在 <p> 之内
let $selectionElem = editor.selection.getSelectionContainerElem()
if ($selectionElem.getNodeName() === 'LI') {
$selectionElem = $selectionElem.parent()
}
if (/^ol|ul$/i.test($selectionElem.getNodeName()) === false) {
return
}
if ($selectionElem.equal($textElem)) {
// 证明是顶级标签,没有被 <p> 包裹
return
}
const $parent = $selectionElem.parent()
if ($parent.equal($textElem)) {
// $parent 是顶级标签,不能删除
return
}
$selectionElem.insertAfter($parent)
$parent.remove()
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
if (editor.cmd.queryCommandState('insertUnOrderedList') || editor.cmd.queryCommandState('insertOrderedList')) {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default List

View File

@ -0,0 +1,63 @@
/*
所有菜单的汇总
*/
// 存储菜单的构造函数
const MenuConstructors = {}
import Bold from './bold/index.js'
MenuConstructors.bold = Bold
import Head from './head/index.js'
MenuConstructors.head = Head
import Link from './link/index.js'
MenuConstructors.link = Link
import Italic from './italic/index.js'
MenuConstructors.italic = Italic
import Redo from './redo/index.js'
MenuConstructors.redo = Redo
import StrikeThrough from './strikethrough/index.js'
MenuConstructors.strikeThrough = StrikeThrough
import Underline from './underline/index.js'
MenuConstructors.underline = Underline
import Undo from './undo/index.js'
MenuConstructors.undo = Undo
import List from './list/index.js'
MenuConstructors.list = List
import Justify from './justify/index.js'
MenuConstructors.justify = Justify
import ForeColor from './foreColor/index.js'
MenuConstructors.foreColor = ForeColor
import BackColor from './backColor/index.js'
MenuConstructors.backColor = BackColor
import Quote from './quote/index.js'
MenuConstructors.quote = Quote
import Code from './code/index.js'
MenuConstructors.code = Code
import Emoticon from './emoticon/index.js'
MenuConstructors.emoticon = Emoticon
import Table from './table/index.js'
MenuConstructors.table = Table
import Video from './video/index.js'
MenuConstructors.video = Video
import Image from './img/index.js'
MenuConstructors.image = Image
// 吐出所有菜单集合
export default MenuConstructors

View File

@ -0,0 +1,195 @@
/*
panel
*/
import $ from '../util/dom-core.js'
import replaceLang from '../util/replace-lang.js'
const emptyFn = () => {}
// 记录已经显示 panel 的菜单
let _isCreatedPanelMenus = []
// 构造函数
function Panel(menu, opt) {
this.menu = menu
this.opt = opt
}
// 原型
Panel.prototype = {
constructor: Panel,
// 显示插入DOM
show: function () {
const menu = this.menu
if (_isCreatedPanelMenus.indexOf(menu) >= 0) {
// 该菜单已经创建了 panel 不能再创建
return
}
const editor = menu.editor
const $body = $('body')
const $textContainerElem = editor.$textContainerElem
const opt = this.opt
// panel 的容器
const $container = $('<div class="w-e-panel-container"></div>')
const width = opt.width || 300 // 默认 300px
$container.css('width', width + 'px')
.css('margin-left', (0 - width)/2 + 'px')
// 添加关闭按钮
const $closeBtn = $('<i class="w-e-icon-close w-e-panel-close"></i>')
$container.append($closeBtn)
$closeBtn.on('click', () => {
this.hide()
})
// 准备 tabs 容器
const $tabTitleContainer = $('<ul class="w-e-panel-tab-title"></ul>')
const $tabContentContainer = $('<div class="w-e-panel-tab-content"></div>')
$container.append($tabTitleContainer).append($tabContentContainer)
// 设置高度
const height = opt.height
if (height) {
$tabContentContainer.css('height', height + 'px').css('overflow-y', 'auto')
}
// tabs
const tabs = opt.tabs || []
const tabTitleArr = []
const tabContentArr = []
tabs.forEach((tab, tabIndex) => {
if (!tab) {
return
}
let title = tab.title || ''
let tpl = tab.tpl || ''
// 替换多语言
title = replaceLang(editor, title)
tpl = replaceLang(editor, tpl)
// 添加到 DOM
const $title = $(`<li class="w-e-item">${title}</li>`)
$tabTitleContainer.append($title)
const $content = $(tpl)
$tabContentContainer.append($content)
// 记录到内存
$title._index = tabIndex
tabTitleArr.push($title)
tabContentArr.push($content)
// 设置 active 项
if (tabIndex === 0) {
$title._active = true
$title.addClass('w-e-active')
} else {
$content.hide()
}
// 绑定 tab 的事件
$title.on('click', e => {
if ($title._active) {
return
}
// 隐藏所有的 tab
tabTitleArr.forEach($title => {
$title._active = false
$title.removeClass('w-e-active')
})
tabContentArr.forEach($content => {
$content.hide()
})
// 显示当前的 tab
$title._active = true
$title.addClass('w-e-active')
$content.show()
})
})
// 绑定关闭事件
$container.on('click', e => {
// 点击时阻止冒泡
e.stopPropagation()
})
$body.on('click', e => {
this.hide()
})
// 添加到 DOM
$textContainerElem.append($container)
// 绑定 opt 的事件,只有添加到 DOM 之后才能绑定成功
tabs.forEach((tab, index) => {
if (!tab) {
return
}
const events = tab.events || []
events.forEach(event => {
const selector = event.selector
const type = event.type
const fn = event.fn || emptyFn
const $content = tabContentArr[index]
$content.find(selector).on(type, (e) => {
e.stopPropagation()
const needToHide = fn(e)
// 执行完事件之后,是否要关闭 panel
if (needToHide) {
this.hide()
}
})
})
})
// focus 第一个 elem
let $inputs = $container.find('input[type=text],textarea')
if ($inputs.length) {
$inputs.get(0).focus()
}
// 添加到属性
this.$container = $container
// 隐藏其他 panel
this._hideOtherPanels()
// 记录该 menu 已经创建了 panel
_isCreatedPanelMenus.push(menu)
},
// 隐藏移除DOM
hide: function () {
const menu = this.menu
const $container = this.$container
if ($container) {
$container.remove()
}
// 将该 menu 记录中移除
_isCreatedPanelMenus = _isCreatedPanelMenus.filter(item => {
if (item === menu) {
return false
} else {
return true
}
})
},
// 一个 panel 展示时,隐藏其他 panel
_hideOtherPanels: function () {
if (!_isCreatedPanelMenus.length) {
return
}
_isCreatedPanelMenus.forEach(menu => {
const panel = menu.panel || {}
if (panel.hide) {
panel.hide()
}
})
}
}
export default Panel

View File

@ -0,0 +1,75 @@
/*
menu - quote
*/
import $ from '../../util/dom-core.js'
import { UA } from '../../util/util.js'
// 构造函数
function Quote(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-quotes-left"><i/>
</div>`
)
this.type = 'click'
// 当前是否 active 状态
this._active = false
}
// 原型
Quote.prototype = {
constructor: Quote,
onClick: function (e) {
const editor = this.editor
const $selectionElem = editor.selection.getSelectionContainerElem()
const nodeName = $selectionElem.getNodeName()
if (!UA.isIE()) {
if (nodeName === 'BLOCKQUOTE') {
// 撤销 quote
editor.cmd.do('formatBlock', '<P>')
} else {
// 转换为 quote
editor.cmd.do('formatBlock', '<BLOCKQUOTE>')
}
return
}
// IE 中不支持 formatBlock <BLOCKQUOTE> ,要用其他方式兼容
let content, $targetELem
if (nodeName === 'P') {
// 将 P 转换为 quote
content = $selectionElem.text()
$targetELem = $(`<blockquote>${content}</blockquote>`)
$targetELem.insertAfter($selectionElem)
$selectionElem.remove()
return
}
if (nodeName === 'BLOCKQUOTE') {
// 撤销 quote
content = $selectionElem.text()
$targetELem = $(`<p>${content}</p>`)
$targetELem.insertAfter($selectionElem)
$selectionElem.remove()
}
},
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
const reg = /^BLOCKQUOTE$/i
const cmdValue = editor.cmd.queryCommandValue('formatBlock')
if (reg.test(cmdValue)) {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Quote

View File

@ -0,0 +1,35 @@
/*
redo-menu
*/
import $ from '../../util/dom-core.js'
// 构造函数
function Redo(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-redo"><i/>
</div>`
)
this.type = 'click'
// 当前是否 active 状态
this._active = false
}
// 原型
Redo.prototype = {
constructor: Redo,
// 点击事件
onClick: function (e) {
// 点击菜单将触发这里
const editor = this.editor
// 执行 redo 命令
editor.cmd.do('redo')
}
}
export default Redo

View File

@ -0,0 +1,60 @@
/*
strikeThrough-menu
*/
import $ from '../../util/dom-core.js'
// 构造函数
function StrikeThrough(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-strikethrough"><i/>
</div>`
)
this.type = 'click'
// 当前是否 active 状态
this._active = false
}
// 原型
StrikeThrough.prototype = {
constructor: StrikeThrough,
// 点击事件
onClick: function (e) {
// 点击菜单将触发这里
const editor = this.editor
const isSeleEmpty = editor.selection.isSelectionEmpty()
if (isSeleEmpty) {
// 选区是空的,插入并选中一个“空白”
editor.selection.createEmptyRange()
}
// 执行 strikeThrough 命令
editor.cmd.do('strikeThrough')
if (isSeleEmpty) {
// 需要将选取折叠起来
editor.selection.collapseRange()
editor.selection.restoreSelection()
}
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
if (editor.cmd.queryCommandState('strikeThrough')) {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default StrikeThrough

View File

@ -0,0 +1,376 @@
/*
menu - table
*/
import $ from '../../util/dom-core.js'
import { getRandom } from '../../util/util.js'
import Panel from '../panel.js'
// 构造函数
function Table(editor) {
this.editor = editor
this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-table2"><i/></div>')
this.type = 'panel'
// 当前是否 active 状态
this._active = false
}
// 原型
Table.prototype = {
constructor: Table,
onClick: function () {
if (this._active) {
// 编辑现有表格
this._createEditPanel()
} else {
// 插入新表格
this._createInsertPanel()
}
},
// 创建插入新表格的 panel
_createInsertPanel: function () {
// 用到的 id
const btnInsertId = getRandom('btn')
const textRowNum = getRandom('row')
const textColNum = getRandom('col')
const panel = new Panel(this, {
width: 250,
// panel 包含多个 tab
tabs: [
{
// 标题
title: '插入表格',
// 模板
tpl: `<div>
<p style="text-align:left; padding:5px 0;">
创建
<input id="${textRowNum}" type="text" value="5" style="width:40px;text-align:center;"/>
<input id="${textColNum}" type="text" value="5" style="width:40px;text-align:center;"/>
列的表格
</p>
<div class="w-e-button-container">
<button id="${btnInsertId}" class="right">插入</button>
</div>
</div>`,
// 事件绑定
events: [
{
// 点击按钮,插入表格
selector: '#' + btnInsertId,
type: 'click',
fn: () => {
const rowNum = parseInt($('#' + textRowNum).val())
const colNum = parseInt($('#' + textColNum).val())
if (rowNum && colNum && rowNum > 0 && colNum > 0) {
// form 数据有效
this._insert(rowNum, colNum)
}
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
}
]
} // first tab end
] // tabs end
}) // panel end
// 展示 panel
panel.show()
// 记录属性
this.panel = panel
},
// 插入表格
_insert: function (rowNum, colNum) {
// 拼接 table 模板
let r, c
let html = '<table border="0" width="100%" cellpadding="0" cellspacing="0">'
for (r = 0; r < rowNum; r++) {
html += '<tr>'
if (r === 0) {
for (c = 0; c < colNum; c++) {
html += '<th>&nbsp;</th>'
}
} else {
for (c = 0; c < colNum; c++) {
html += '<td>&nbsp;</td>'
}
}
html += '</tr>'
}
html += '</table><p><br></p>'
// 执行命令
const editor = this.editor
editor.cmd.do('insertHTML', html)
// 防止 firefox 下出现 resize 的控制点
editor.cmd.do('enableObjectResizing', false)
editor.cmd.do('enableInlineTableEditing', false)
},
// 创建编辑表格的 panel
_createEditPanel: function () {
// 可用的 id
const addRowBtnId = getRandom('add-row')
const addColBtnId = getRandom('add-col')
const delRowBtnId = getRandom('del-row')
const delColBtnId = getRandom('del-col')
const delTableBtnId = getRandom('del-table')
// 创建 panel 对象
const panel = new Panel(this, {
width: 320,
// panel 包含多个 tab
tabs: [
{
// 标题
title: '编辑表格',
// 模板
tpl: `<div>
<div class="w-e-button-container" style="border-bottom:1px solid #f1f1f1;padding-bottom:5px;margin-bottom:5px;">
<button id="${addRowBtnId}" class="left">增加行</button>
<button id="${delRowBtnId}" class="red left">删除行</button>
<button id="${addColBtnId}" class="left">增加列</button>
<button id="${delColBtnId}" class="red left">删除列</button>
</div>
<div class="w-e-button-container">
<button id="${delTableBtnId}" class="gray left">删除表格</button>
</dv>
</div>`,
// 事件绑定
events: [
{
// 增加行
selector: '#' + addRowBtnId,
type: 'click',
fn: () => {
this._addRow()
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
},
{
// 增加列
selector: '#' + addColBtnId,
type: 'click',
fn: () => {
this._addCol()
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
},
{
// 删除行
selector: '#' + delRowBtnId,
type: 'click',
fn: () => {
this._delRow()
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
},
{
// 删除列
selector: '#' + delColBtnId,
type: 'click',
fn: () => {
this._delCol()
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
},
{
// 删除表格
selector: '#' + delTableBtnId,
type: 'click',
fn: () => {
this._delTable()
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
}
]
}
]
})
// 显示 panel
panel.show()
},
// 获取选中的单元格的位置信息
_getLocationData: function () {
const result = {}
const editor = this.editor
const $selectionELem = editor.selection.getSelectionContainerElem()
if (!$selectionELem) {
return
}
const nodeName = $selectionELem.getNodeName()
if (nodeName !== 'TD' && nodeName !== 'TH') {
return
}
// 获取 td index
const $tr = $selectionELem.parent()
const $tds = $tr.children()
const tdLength = $tds.length
$tds.forEach((td, index) => {
if (td === $selectionELem[0]) {
// 记录并跳出循环
result.td = {
index: index,
elem: td,
length: tdLength
}
return false
}
})
// 获取 tr index
const $tbody = $tr.parent()
const $trs = $tbody.children()
const trLength = $trs.length
$trs.forEach((tr, index) => {
if (tr === $tr[0]) {
// 记录并跳出循环
result.tr = {
index: index,
elem: tr,
length: trLength
}
return false
}
})
// 返回结果
return result
},
// 增加行
_addRow: function () {
// 获取当前单元格的位置信息
const locationData = this._getLocationData()
if (!locationData) {
return
}
const trData = locationData.tr
const $currentTr = $(trData.elem)
const tdData = locationData.td
const tdLength = tdData.length
// 拼接即将插入的字符串
const newTr = document.createElement('tr')
let tpl = '', i
for (i = 0; i < tdLength; i++) {
tpl += '<td>&nbsp;</td>'
}
newTr.innerHTML = tpl
// 插入
$(newTr).insertAfter($currentTr)
},
// 增加列
_addCol: function () {
// 获取当前单元格的位置信息
const locationData = this._getLocationData()
if (!locationData) {
return
}
const trData = locationData.tr
const tdData = locationData.td
const tdIndex = tdData.index
const $currentTr = $(trData.elem)
const $trParent = $currentTr.parent()
const $trs = $trParent.children()
// 遍历所有行
$trs.forEach(tr => {
const $tr = $(tr)
const $tds = $tr.children()
const $currentTd = $tds.get(tdIndex)
const name = $currentTd.getNodeName().toLowerCase()
// new 一个 td并插入
const newTd = document.createElement(name)
$(newTd).insertAfter($currentTd)
})
},
// 删除行
_delRow: function () {
// 获取当前单元格的位置信息
const locationData = this._getLocationData()
if (!locationData) {
return
}
const trData = locationData.tr
const $currentTr = $(trData.elem)
$currentTr.remove()
},
// 删除列
_delCol: function () {
// 获取当前单元格的位置信息
const locationData = this._getLocationData()
if (!locationData) {
return
}
const trData = locationData.tr
const tdData = locationData.td
const tdIndex = tdData.index
const $currentTr = $(trData.elem)
const $trParent = $currentTr.parent()
const $trs = $trParent.children()
// 遍历所有行
$trs.forEach(tr => {
const $tr = $(tr)
const $tds = $tr.children()
const $currentTd = $tds.get(tdIndex)
// 删除
$currentTd.remove()
})
},
// 删除表格
_delTable: function () {
const editor = this.editor
const $selectionELem = editor.selection.getSelectionContainerElem()
if (!$selectionELem) {
return
}
const $table = $selectionELem.parentUntil('table')
if (!$table) {
return
}
$table.remove()
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
const $selectionELem = editor.selection.getSelectionContainerElem()
if (!$selectionELem) {
return
}
const nodeName = $selectionELem.getNodeName()
if (nodeName === 'TD' || nodeName === 'TH') {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Table

View File

@ -0,0 +1,60 @@
/*
underline-menu
*/
import $ from '../../util/dom-core.js'
// 构造函数
function Underline(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-underline"><i/>
</div>`
)
this.type = 'click'
// 当前是否 active 状态
this._active = false
}
// 原型
Underline.prototype = {
constructor: Underline,
// 点击事件
onClick: function (e) {
// 点击菜单将触发这里
const editor = this.editor
const isSeleEmpty = editor.selection.isSelectionEmpty()
if (isSeleEmpty) {
// 选区是空的,插入并选中一个“空白”
editor.selection.createEmptyRange()
}
// 执行 underline 命令
editor.cmd.do('underline')
if (isSeleEmpty) {
// 需要将选取折叠起来
editor.selection.collapseRange()
editor.selection.restoreSelection()
}
},
// 试图改变 active 状态
tryChangeActive: function (e) {
const editor = this.editor
const $elem = this.$elem
if (editor.cmd.queryCommandState('underline')) {
this._active = true
$elem.addClass('w-e-active')
} else {
this._active = false
$elem.removeClass('w-e-active')
}
}
}
export default Underline

View File

@ -0,0 +1,35 @@
/*
undo-menu
*/
import $ from '../../util/dom-core.js'
// 构造函数
function Undo(editor) {
this.editor = editor
this.$elem = $(
`<div class="w-e-menu">
<i class="w-e-icon-undo"><i/>
</div>`
)
this.type = 'click'
// 当前是否 active 状态
this._active = false
}
// 原型
Undo.prototype = {
constructor: Undo,
// 点击事件
onClick: function (e) {
// 点击菜单将触发这里
const editor = this.editor
// 执行 undo 命令
editor.cmd.do('undo')
}
}
export default Undo

View File

@ -0,0 +1,86 @@
/*
menu - video
*/
import $ from '../../util/dom-core.js'
import { getRandom } from '../../util/util.js'
import Panel from '../panel.js'
// 构造函数
function Video(editor) {
this.editor = editor
this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-play"><i/></div>')
this.type = 'panel'
// 当前是否 active 状态
this._active = false
}
// 原型
Video.prototype = {
constructor: Video,
onClick: function () {
this._createPanel()
},
_createPanel: function () {
// 创建 id
const textValId = getRandom('text-val')
const btnId = getRandom('btn')
// 创建 panel
const panel = new Panel(this, {
width: 350,
// 一个 panel 多个 tab
tabs: [
{
// 标题
title: '插入视频',
// 模板
tpl: `<div>
<input id="${textValId}" type="text" class="block" placeholder="格式如<iframe src=... ><\/iframe>"/>
<div class="w-e-button-container">
<button id="${btnId}" class="right">插入</button>
</div>
</div>`,
// 事件绑定
events: [
{
selector: '#' + btnId,
type: 'click',
fn: () => {
const $text = $('#' + textValId)
const val = $text.val().trim()
// 测试用视频地址
// <iframe height=498 width=510 src='http://player.youku.com/embed/XMjcwMzc3MzM3Mg==' frameborder=0 'allowfullscreen'></iframe>
if (val) {
// 插入视频
this._insert(val)
}
// 返回 true表示该事件执行完之后panel 要关闭。否则 panel 不会关闭
return true
}
}
]
} // first tab end
] // tabs end
}) // panel end
// 显示 panel
panel.show()
// 记录属性
this.panel = panel
},
// 插入视频
_insert: function (val) {
const editor = this.editor
editor.cmd.do('insertHTML', val + '<p><br></p>')
}
}
export default Video

View File

@ -0,0 +1,186 @@
/*
selection range API
*/
import $ from '../util/dom-core.js'
import { UA } from '../util/util.js'
// 构造函数
function API(editor) {
this.editor = editor
this._currentRange = null
}
// 修改原型
API.prototype = {
constructor: API,
// 获取 range 对象
getRange: function () {
return this._currentRange
},
// 保存选区
saveRange: function (_range) {
if (_range) {
// 保存已有选区
this._currentRange = _range
return
}
// 获取当前的选区
const selection = window.getSelection()
if (selection.rangeCount === 0) {
return
}
const range = selection.getRangeAt(0)
// 判断选区内容是否在编辑内容之内
const $containerElem = this.getSelectionContainerElem(range)
if (!$containerElem) {
return
}
const editor = this.editor
const $textElem = editor.$textElem
if ($textElem.isContain($containerElem)) {
// 是编辑内容之内的
this._currentRange = range
}
},
// 折叠选区
collapseRange: function (toStart) {
if (toStart == null) {
// 默认为 false
toStart = false
}
const range = this._currentRange
if (range) {
range.collapse(toStart)
}
},
// 选中区域的文字
getSelectionText: function () {
const range = this._currentRange
if (range) {
return this._currentRange.toString()
} else {
return ''
}
},
// 选区的 $Elem
getSelectionContainerElem: function (range) {
range = range || this._currentRange
let elem
if (range) {
elem = range.commonAncestorContainer
return $(
elem.nodeType === 1 ? elem : elem.parentNode
)
}
},
getSelectionStartElem: function (range) {
range = range || this._currentRange
let elem
if (range) {
elem = range.startContainer
return $(
elem.nodeType === 1 ? elem : elem.parentNode
)
}
},
getSelectionEndElem: function (range) {
range = range || this._currentRange
let elem
if (range) {
elem = range.endContainer
return $(
elem.nodeType === 1 ? elem : elem.parentNode
)
}
},
// 选区是否为空
isSelectionEmpty: function () {
const range = this._currentRange
if (range && range.startContainer) {
if (range.startContainer === range.endContainer) {
if (range.startOffset === range.endOffset) {
return true
}
}
}
return false
},
// 恢复选区
restoreSelection: function () {
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(this._currentRange)
},
// 创建一个空白(即 &#8203 字符)选区
createEmptyRange: function () {
const editor = this.editor
const range = this.getRange()
let $elem
if (!range) {
// 当前无 range
return
}
if (!this.isSelectionEmpty()) {
// 当前选区必须没有内容才可以
return
}
try {
// 目前只支持 webkit 内核
if (UA.isWebkit()) {
// 插入 &#8203
editor.cmd.do('insertHTML', '&#8203;')
// 修改 offset 位置
range.setEnd(range.endContainer, range.endOffset + 1)
// 存储
this.saveRange(range)
} else {
$elem = $('<strong>&#8203;</strong>')
editor.cmd.do('insertElem', $elem)
this.createRangeByElem($elem, true)
}
} catch (ex) {
// 部分情况下会报错,兼容一下
}
},
// 根据 $Elem 设置选区
createRangeByElem: function ($elem, toStart, isContent) {
// $elem - 经过封装的 elem
// toStart - true 开始位置false 结束位置
// isContent - 是否选中Elem的内容
if (!$elem.length) {
return
}
const elem = $elem[0]
const range = document.createRange()
if (isContent) {
range.selectNodeContents(elem)
} else {
range.selectNode(elem)
}
if (typeof toStart === 'boolean') {
range.collapse(toStart)
}
// 存储 range
this.saveRange(range)
}
}
export default API

View File

@ -0,0 +1,551 @@
/*
编辑区域
*/
import $ from '../util/dom-core.js'
import { getPasteText, getPasteHtml, getPasteImgs } from '../util/paste-handle.js'
import { UA, isFunction } from '../util/util.js'
// 获取一个 elem.childNodes 的 JSON 数据
function getChildrenJSON($elem) {
const result = []
const $children = $elem.childNodes() || [] // 注意 childNodes() 可以获取文本节点
$children.forEach(curElem => {
let elemResult
const nodeType = curElem.nodeType
// 文本节点
if (nodeType === 3) {
elemResult = curElem.textContent
}
// 普通 DOM 节点
if (nodeType === 1) {
elemResult = {}
// tag
elemResult.tag = curElem.nodeName.toLowerCase()
// attr
const attrData = []
const attrList = curElem.attributes || {}
const attrListLength = attrList.length || 0
for (let i = 0; i < attrListLength; i++) {
const attr = attrList[i]
attrData.push({
name: attr.name,
value: attr.value
})
}
elemResult.attrs = attrData
// children递归
elemResult.children = getChildrenJSON($(curElem))
}
result.push(elemResult)
})
return result
}
// 构造函数
function Text(editor) {
this.editor = editor
}
// 修改原型
Text.prototype = {
constructor: Text,
// 初始化
init: function () {
// 绑定事件
this._bindEvent()
},
// 清空内容
clear: function () {
this.html('<p><br></p>')
},
// 获取 设置 html
html: function (val) {
const editor = this.editor
const $textElem = editor.$textElem
let html
if (val == null) {
html = $textElem.html()
// 未选中任何内容的时候点击“加粗”或者“斜体”等按钮,就得需要一个空的占位符 &#8203 ,这里替换掉
html = html.replace(/\u200b/gm, '')
return html
} else {
$textElem.html(val)
// 初始化选取,将光标定位到内容尾部
editor.initSelection()
}
},
// 获取 JSON
getJSON: function () {
const editor = this.editor
const $textElem = editor.$textElem
return getChildrenJSON($textElem)
},
// 获取 设置 text
text: function (val) {
const editor = this.editor
const $textElem = editor.$textElem
let text
if (val == null) {
text = $textElem.text()
// 未选中任何内容的时候点击“加粗”或者“斜体”等按钮,就得需要一个空的占位符 &#8203 ,这里替换掉
text = text.replace(/\u200b/gm, '')
return text
} else {
$textElem.text(`<p>${val}</p>`)
// 初始化选取,将光标定位到内容尾部
editor.initSelection()
}
},
// 追加内容
append: function (html) {
const editor = this.editor
const $textElem = editor.$textElem
$textElem.append($(html))
// 初始化选取,将光标定位到内容尾部
editor.initSelection()
},
// 绑定事件
_bindEvent: function () {
// 实时保存选取
this._saveRangeRealTime()
// 按回车建时的特殊处理
this._enterKeyHandle()
// 清空时保留 <p><br></p>
this._clearHandle()
// 粘贴事件(粘贴文字,粘贴图片)
this._pasteHandle()
// tab 特殊处理
this._tabHandle()
// img 点击
this._imgHandle()
// 拖拽事件
this._dragHandle()
},
// 实时保存选取
_saveRangeRealTime: function () {
const editor = this.editor
const $textElem = editor.$textElem
// 保存当前的选区
function saveRange(e) {
// 随时保存选区
editor.selection.saveRange()
// 更新按钮 ative 状态
editor.menus.changeActive()
}
// 按键后保存
$textElem.on('keyup', saveRange)
$textElem.on('mousedown', e => {
// mousedown 状态下,鼠标滑动到编辑区域外面,也需要保存选区
$textElem.on('mouseleave', saveRange)
})
$textElem.on('mouseup', e => {
saveRange()
// 在编辑器区域之内完成点击,取消鼠标滑动到编辑区外面的事件
$textElem.off('mouseleave', saveRange)
})
},
// 按回车键时的特殊处理
_enterKeyHandle: function () {
const editor = this.editor
const $textElem = editor.$textElem
function insertEmptyP ($selectionElem) {
const $p = $('<p><br></p>')
$p.insertBefore($selectionElem)
editor.selection.createRangeByElem($p, true)
editor.selection.restoreSelection()
$selectionElem.remove()
}
// 将回车之后生成的非 <p> 的顶级标签,改为 <p>
function pHandle(e) {
const $selectionElem = editor.selection.getSelectionContainerElem()
const $parentElem = $selectionElem.parent()
if ($parentElem.html() === '<code><br></code>') {
// 回车之前光标所在一个 <p><code>.....</code></p> ,忽然回车生成一个空的 <p><code><br></code></p>
// 而且继续回车跳不出去,因此只能特殊处理
insertEmptyP($selectionElem)
return
}
if (!$parentElem.equal($textElem)) {
// 不是顶级标签
return
}
const nodeName = $selectionElem.getNodeName()
if (nodeName === 'P') {
// 当前的标签是 P ,不用做处理
return
}
if ($selectionElem.text()) {
// 有内容,不做处理
return
}
// 插入 <p> ,并将选取定位到 <p>,删除当前标签
insertEmptyP($selectionElem)
}
$textElem.on('keyup', e => {
if (e.keyCode !== 13) {
// 不是回车键
return
}
// 将回车之后生成的非 <p> 的顶级标签,改为 <p>
pHandle(e)
})
// <pre><code></code></pre> 回车时 特殊处理
function codeHandle(e) {
const $selectionElem = editor.selection.getSelectionContainerElem()
if (!$selectionElem) {
return
}
const $parentElem = $selectionElem.parent()
const selectionNodeName = $selectionElem.getNodeName()
const parentNodeName = $parentElem.getNodeName()
if (selectionNodeName !== 'CODE' || parentNodeName !== 'PRE') {
// 不符合要求 忽略
return
}
if (!editor.cmd.queryCommandSupported('insertHTML')) {
// 必须原生支持 insertHTML 命令
return
}
// 处理:光标定位到代码末尾,联系点击两次回车,即跳出代码块
if (editor._willBreakCode === true) {
// 此时可以跳出代码块
// 插入 <p> ,并将选取定位到 <p>
const $p = $('<p><br></p>')
$p.insertAfter($parentElem)
editor.selection.createRangeByElem($p, true)
editor.selection.restoreSelection()
// 修改状态
editor._willBreakCode = false
e.preventDefault()
return
}
const _startOffset = editor.selection.getRange().startOffset
// 处理:回车时,不能插入 <br> 而是插入 \n ,因为是在 pre 标签里面
editor.cmd.do('insertHTML', '\n')
editor.selection.saveRange()
if (editor.selection.getRange().startOffset === _startOffset) {
// 没起作用,再来一遍
editor.cmd.do('insertHTML', '\n')
}
const codeLength = $selectionElem.html().length
if (editor.selection.getRange().startOffset + 1 === codeLength) {
// 说明光标在代码最后的位置,执行了回车操作
// 记录下来,以便下次回车时候跳出 code
editor._willBreakCode = true
}
// 阻止默认行为
e.preventDefault()
}
$textElem.on('keydown', e => {
if (e.keyCode !== 13) {
// 不是回车键
// 取消即将跳转代码块的记录
editor._willBreakCode = false
return
}
// <pre><code></code></pre> 回车时 特殊处理
codeHandle(e)
})
},
// 清空时保留 <p><br></p>
_clearHandle: function () {
const editor = this.editor
const $textElem = editor.$textElem
$textElem.on('keydown', e => {
if (e.keyCode !== 8) {
return
}
const txtHtml = $textElem.html().toLowerCase().trim()
if (txtHtml === '<p><br></p>') {
// 最后剩下一个空行,就不再删除了
e.preventDefault()
return
}
})
$textElem.on('keyup', e => {
if (e.keyCode !== 8) {
return
}
let $p
const txtHtml = $textElem.html().toLowerCase().trim()
// firefox 时用 txtHtml === '<br>' 判断,其他用 !txtHtml 判断
if (!txtHtml || txtHtml === '<br>') {
// 内容空了
$p = $('<p><br/></p>')
$textElem.html('') // 一定要先清空,否则在 firefox 下有问题
$textElem.append($p)
editor.selection.createRangeByElem($p, false, true)
editor.selection.restoreSelection()
}
})
},
// 粘贴事件(粘贴文字 粘贴图片)
_pasteHandle: function () {
const editor = this.editor
const config = editor.config
const pasteFilterStyle = config.pasteFilterStyle
const pasteTextHandle = config.pasteTextHandle
const $textElem = editor.$textElem
// 粘贴图片、文本的事件,每次只能执行一个
// 判断该次粘贴事件是否可以执行
let pasteTime = 0
function canDo() {
var now = Date.now()
var flag = false
if (now - pasteTime >= 500) {
// 间隔大于 500 ms ,可以执行
flag = true
}
pasteTime = now
return flag
}
function resetTime() {
pasteTime = 0
}
// 粘贴文字
$textElem.on('paste', e => {
if (UA.isIE()) {
return
} else {
// 阻止默认行为,使用 execCommand 的粘贴命令
e.preventDefault()
}
// 粘贴图片和文本,只能同时使用一个
if (!canDo()) {
return
}
// 获取粘贴的文字
let pasteHtml = getPasteHtml(e, pasteFilterStyle)
let pasteText = getPasteText(e)
pasteText = pasteText.replace(/\n/gm, '<br>')
const $selectionElem = editor.selection.getSelectionContainerElem()
if (!$selectionElem) {
return
}
const nodeName = $selectionElem.getNodeName()
// code 中只能粘贴纯文本
if (nodeName === 'CODE' || nodeName === 'PRE') {
if (pasteTextHandle && isFunction(pasteTextHandle)) {
// 用户自定义过滤处理粘贴内容
pasteText = '' + (pasteTextHandle(pasteText) || '')
}
editor.cmd.do('insertHTML', `<p>${pasteText}</p>`)
return
}
// 先放开注释,有问题再追查 ————
// // 表格中忽略,可能会出现异常问题
// if (nodeName === 'TD' || nodeName === 'TH') {
// return
// }
if (!pasteHtml) {
// 没有内容,可继续执行下面的图片粘贴
resetTime()
return
}
try {
// firefox 中,获取的 pasteHtml 可能是没有 <ul> 包裹的 <li>
// 因此执行 insertHTML 会报错
if (pasteTextHandle && isFunction(pasteTextHandle)) {
// 用户自定义过滤处理粘贴内容
pasteHtml = '' + (pasteTextHandle(pasteHtml) || '')
}
editor.cmd.do('insertHTML', pasteHtml)
} catch (ex) {
// 此时使用 pasteText 来兼容一下
if (pasteTextHandle && isFunction(pasteTextHandle)) {
// 用户自定义过滤处理粘贴内容
pasteText = '' + (pasteTextHandle(pasteText) || '')
}
editor.cmd.do('insertHTML', `<p>${pasteText}</p>`)
}
})
// 粘贴图片
$textElem.on('paste', e => {
if (UA.isIE()) {
return
} else {
e.preventDefault()
}
// 粘贴图片和文本,只能同时使用一个
if (!canDo()) {
return
}
// 获取粘贴的图片
const pasteFiles = getPasteImgs(e)
if (!pasteFiles || !pasteFiles.length) {
return
}
// 获取当前的元素
const $selectionElem = editor.selection.getSelectionContainerElem()
if (!$selectionElem) {
return
}
const nodeName = $selectionElem.getNodeName()
// code 中粘贴忽略
if (nodeName === 'CODE' || nodeName === 'PRE') {
return
}
// 上传图片
const uploadImg = editor.uploadImg
uploadImg.uploadImg(pasteFiles)
})
},
// tab 特殊处理
_tabHandle: function () {
const editor = this.editor
const $textElem = editor.$textElem
$textElem.on('keydown', e => {
if (e.keyCode !== 9) {
return
}
if (!editor.cmd.queryCommandSupported('insertHTML')) {
// 必须原生支持 insertHTML 命令
return
}
const $selectionElem = editor.selection.getSelectionContainerElem()
if (!$selectionElem) {
return
}
const $parentElem = $selectionElem.parent()
const selectionNodeName = $selectionElem.getNodeName()
const parentNodeName = $parentElem.getNodeName()
if (selectionNodeName === 'CODE' && parentNodeName === 'PRE') {
// <pre><code> 里面
editor.cmd.do('insertHTML', ' ')
} else {
// 普通文字
editor.cmd.do('insertHTML', '&nbsp;&nbsp;&nbsp;&nbsp;')
}
e.preventDefault()
})
},
// img 点击
_imgHandle: function () {
const editor = this.editor
const $textElem = editor.$textElem
// 为图片增加 selected 样式
$textElem.on('click', 'img', function (e) {
const img = this
const $img = $(img)
if ($img.attr('data-w-e') === '1') {
// 是表情图片,忽略
return
}
// 记录当前点击过的图片
editor._selectedImg = $img
// 修改选区并 restore ,防止用户此时点击退格键,会删除其他内容
editor.selection.createRangeByElem($img)
editor.selection.restoreSelection()
})
// 去掉图片的 selected 样式
$textElem.on('click keyup', e => {
if (e.target.matches('img')) {
// 点击的是图片,忽略
return
}
// 删除记录
editor._selectedImg = null
})
},
// 拖拽事件
_dragHandle: function () {
const editor = this.editor
// 禁用 document 拖拽事件
const $document = $(document)
$document.on('dragleave drop dragenter dragover', function (e) {
e.preventDefault()
})
// 添加编辑区域拖拽事件
const $textElem = editor.$textElem
$textElem.on('drop', function (e) {
e.preventDefault()
const files = e.dataTransfer && e.dataTransfer.files
if (!files || !files.length) {
return
}
// 上传图片
const uploadImg = editor.uploadImg
uploadImg.uploadImg(files)
})
}
}
export default Text

View File

@ -0,0 +1,488 @@
/*
DOM 操作 API
*/
// 根据 html 代码片段创建 dom 对象
function createElemByHTML(html) {
let div
div = document.createElement('div')
div.innerHTML = html
return div.children
}
// 是否是 DOM List
function isDOMList(selector) {
if (!selector) {
return false
}
if (selector instanceof HTMLCollection || selector instanceof NodeList) {
return true
}
return false
}
// 封装 document.querySelectorAll
function querySelectorAll(selector) {
const result = document.querySelectorAll(selector)
if (isDOMList(result)) {
return result
} else {
return [result]
}
}
// 记录所有的事件绑定
const eventList = []
// 创建构造函数
function DomElement(selector) {
if (!selector) {
return
}
// selector 本来就是 DomElement 对象,直接返回
if (selector instanceof DomElement) {
return selector
}
this.selector = selector
const nodeType = selector.nodeType
// 根据 selector 得出的结果(如 DOMDOM List
let selectorResult = []
if (nodeType === 9) {
// document 节点
selectorResult = [selector]
} else if (nodeType === 1) {
// 单个 DOM 节点
selectorResult = [selector]
} else if (isDOMList(selector) || selector instanceof Array) {
// DOM List 或者数组
selectorResult = selector
} else if (typeof selector === 'string') {
// 字符串
selector = selector.replace('/\n/mg', '').trim()
if (selector.indexOf('<') === 0) {
// 如 <div>
selectorResult = createElemByHTML(selector)
} else {
// 如 #id .class
selectorResult = querySelectorAll(selector)
}
}
const length = selectorResult.length
if (!length) {
// 空数组
return this
}
// 加入 DOM 节点
let i
for (i = 0; i < length; i++) {
this[i] = selectorResult[i]
}
this.length = length
}
// 修改原型
DomElement.prototype = {
constructor: DomElement,
// 类数组forEach
forEach: function (fn) {
let i
for (i = 0; i < this.length; i++) {
const elem = this[i]
const result = fn.call(elem, elem, i)
if (result === false) {
break
}
}
return this
},
// clone
clone: function (deep) {
const cloneList = []
this.forEach(elem => {
cloneList.push(elem.cloneNode(!!deep))
})
return $(cloneList)
},
// 获取第几个元素
get: function (index) {
const length = this.length
if (index >= length) {
index = index % length
}
return $(this[index])
},
// 第一个
first: function () {
return this.get(0)
},
// 最后一个
last: function () {
const length = this.length
return this.get(length - 1)
},
// 绑定事件
on: function (type, selector, fn) {
// selector 不为空,证明绑定事件要加代理
if (!fn) {
fn = selector
selector = null
}
// type 是否有多个
let types = []
types = type.split(/\s+/)
return this.forEach(elem => {
types.forEach(type => {
if (!type) {
return
}
// 记录下,方便后面解绑
eventList.push({
elem: elem,
type: type,
fn: fn
})
if (!selector) {
// 无代理
elem.addEventListener(type, fn)
return
}
// 有代理
elem.addEventListener(type, e => {
const target = e.target
if (target.matches(selector)) {
fn.call(target, e)
}
})
})
})
},
// 取消事件绑定
off: function (type, fn) {
return this.forEach(elem => {
elem.removeEventListener(type, fn)
})
},
// 获取/设置 属性
attr: function (key, val) {
if (val == null) {
// 获取值
return this[0].getAttribute(key)
} else {
// 设置值
return this.forEach(elem => {
elem.setAttribute(key, val)
})
}
},
// 添加 class
addClass: function(className) {
if (!className) {
return this
}
return this.forEach(elem => {
let arr
if (elem.className) {
// 解析当前 className 转换为数组
arr = elem.className.split(/\s/)
arr = arr.filter(item => {
return !!item.trim()
})
// 添加 class
if (arr.indexOf(className) < 0) {
arr.push(className)
}
// 修改 elem.class
elem.className = arr.join(' ')
} else {
elem.className = className
}
})
},
// 删除 class
removeClass: function (className) {
if (!className) {
return this
}
return this.forEach(elem => {
let arr
if (elem.className) {
// 解析当前 className 转换为数组
arr = elem.className.split(/\s/)
arr = arr.filter(item => {
item = item.trim()
// 删除 class
if (!item || item === className) {
return false
}
return true
})
// 修改 elem.class
elem.className = arr.join(' ')
}
})
},
// 修改 css
css: function (key, val) {
const currentStyle = `${key}:${val};`
return this.forEach(elem => {
const style = (elem.getAttribute('style') || '').trim()
let styleArr, resultArr = []
if (style) {
// 将 style 按照 ; 拆分为数组
styleArr = style.split(';')
styleArr.forEach(item => {
// 对每项样式,按照 : 拆分为 key 和 value
let arr = item.split(':').map(i => {
return i.trim()
})
if (arr.length === 2) {
resultArr.push(arr[0] + ':' + arr[1])
}
})
// 替换或者新增
resultArr = resultArr.map(item => {
if (item.indexOf(key) === 0) {
return currentStyle
} else {
return item
}
})
if (resultArr.indexOf(currentStyle) < 0) {
resultArr.push(currentStyle)
}
// 结果
elem.setAttribute('style', resultArr.join('; '))
} else {
// style 无值
elem.setAttribute('style', currentStyle)
}
})
},
// 显示
show: function () {
return this.css('display', 'block')
},
// 隐藏
hide: function () {
return this.css('display', 'none')
},
// 获取子节点
children: function () {
const elem = this[0]
if (!elem) {
return null
}
return $(elem.children)
},
// 获取子节点(包括文本节点)
childNodes: function () {
const elem = this[0]
if (!elem) {
return null
}
return $(elem.childNodes)
},
// 增加子节点
append: function($children) {
return this.forEach(elem => {
$children.forEach(child => {
elem.appendChild(child)
})
})
},
// 移除当前节点
remove: function () {
return this.forEach(elem => {
if (elem.remove) {
elem.remove()
} else {
const parent = elem.parentElement
parent && parent.removeChild(elem)
}
})
},
// 是否包含某个子节点
isContain: function ($child) {
const elem = this[0]
const child = $child[0]
return elem.contains(child)
},
// 尺寸数据
getSizeData: function () {
const elem = this[0]
return elem.getBoundingClientRect() // 可得到 bottom height left right top width 的数据
},
// 封装 nodeName
getNodeName: function () {
const elem = this[0]
return elem.nodeName
},
// 从当前元素查找
find: function (selector) {
const elem = this[0]
return $(elem.querySelectorAll(selector))
},
// 获取当前元素的 text
text: function (val) {
if (!val) {
// 获取 text
const elem = this[0]
return elem.innerHTML.replace(/<.*?>/g, () => '')
} else {
// 设置 text
return this.forEach(elem => {
elem.innerHTML = val
})
}
},
// 获取 html
html: function (value) {
const elem = this[0]
if (value == null) {
return elem.innerHTML
} else {
elem.innerHTML = value
return this
}
},
// 获取 value
val: function () {
const elem = this[0]
return elem.value.trim()
},
// focus
focus: function () {
return this.forEach(elem => {
elem.focus()
})
},
// parent
parent: function () {
const elem = this[0]
return $(elem.parentElement)
},
// parentUntil 找到符合 selector 的父节点
parentUntil: function (selector, _currentElem) {
const results = document.querySelectorAll(selector)
const length = results.length
if (!length) {
// 传入的 selector 无效
return null
}
const elem = _currentElem || this[0]
if (elem.nodeName === 'BODY') {
return null
}
const parent = elem.parentElement
let i
for (i = 0; i < length; i++) {
if (parent === results[i]) {
// 找到,并返回
return $(parent)
}
}
// 继续查找
return this.parentUntil(selector, parent)
},
// 判断两个 elem 是否相等
equal: function ($elem) {
if ($elem.nodeType === 1) {
return this[0] === $elem
} else {
return this[0] === $elem[0]
}
},
// 将该元素插入到某个元素前面
insertBefore: function (selector) {
const $referenceNode = $(selector)
const referenceNode = $referenceNode[0]
if (!referenceNode) {
return this
}
return this.forEach(elem => {
const parent = referenceNode.parentNode
parent.insertBefore(elem, referenceNode)
})
},
// 将该元素插入到某个元素后面
insertAfter: function (selector) {
const $referenceNode = $(selector)
const referenceNode = $referenceNode[0]
if (!referenceNode) {
return this
}
return this.forEach(elem => {
const parent = referenceNode.parentNode
if (parent.lastChild === referenceNode) {
// 最后一个元素
parent.appendChild(elem)
} else {
// 不是最后一个元素
parent.insertBefore(elem, referenceNode.nextSibling)
}
})
}
}
// new 一个对象
function $(selector) {
return new DomElement(selector)
}
// 解绑所有事件,用于销毁编辑器
$.offAll = function () {
eventList.forEach(item => {
const elem = item.elem
const type = item.type
const fn = item.fn
// 解绑
elem.removeEventListener(type, fn)
})
}
export default $

View File

@ -0,0 +1,86 @@
/*
粘贴信息的处理
*/
import $ from './dom-core.js'
import { replaceHtmlSymbol } from './util.js'
import { objForEach } from './util.js'
// 获取粘贴的纯文本
export function getPasteText(e) {
const clipboardData = e.clipboardData || (e.originalEvent && e.originalEvent.clipboardData)
let pasteText
if (clipboardData == null) {
pasteText = window.clipboardData && window.clipboardData.getData('text')
} else {
pasteText = clipboardData.getData('text/plain')
}
return replaceHtmlSymbol(pasteText)
}
// 获取粘贴的html
export function getPasteHtml(e, filterStyle) {
const clipboardData = e.clipboardData || (e.originalEvent && e.originalEvent.clipboardData)
let pasteText, pasteHtml
if (clipboardData == null) {
pasteText = window.clipboardData && window.clipboardData.getData('text')
} else {
pasteText = clipboardData.getData('text/plain')
pasteHtml = clipboardData.getData('text/html')
}
if (!pasteHtml && pasteText) {
pasteHtml = '<p>' + replaceHtmlSymbol(pasteText) + '</p>'
}
if (!pasteHtml) {
return
}
// 过滤word中状态过来的无用字符
const docSplitHtml = pasteHtml.split('</html>')
if (docSplitHtml.length === 2) {
pasteHtml = docSplitHtml[0]
}
// 过滤无用标签
pasteHtml = pasteHtml.replace(/<(meta|script|link).+?>/igm, '')
// 去掉注释
pasteHtml = pasteHtml.replace(/<!--.*?-->/mg, '')
// 过滤 data-xxx 属性
pasteHtml = pasteHtml.replace(/\s?data-.+?=('|").+?('|")/igm, '')
if (filterStyle) {
// 过滤样式
pasteHtml = pasteHtml.replace(/\s?(class|style)=('|").+?('|")/igm, '')
} else {
// 保留样式
pasteHtml = pasteHtml.replace(/\s?class=('|").+?('|")/igm, '')
}
return pasteHtml
}
// 获取粘贴的图片文件
export function getPasteImgs(e) {
const result = []
const txt = getPasteText(e)
if (txt) {
// 有文字,就忽略图片
return result
}
const clipboardData = e.clipboardData || (e.originalEvent && e.originalEvent.clipboardData) || {}
const items = clipboardData.items
if (!items) {
return result
}
objForEach(items, (key, value) => {
const type = value.type
if (/image/i.test(type)) {
result.push(value.getAsFile())
}
})
return result
}

View File

@ -0,0 +1,48 @@
/*
poly-fill
*/
export default function () {
// Object.assign
if (typeof Object.assign != 'function') {
Object.assign = function(target, varArgs) { // .length of function is 2
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object')
}
var to = Object(target)
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index]
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey]
}
}
}
}
return to
}
}
// IE 中兼容 Element.prototype.matches
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
while (--i >= 0 && matches.item(i) !== this) {}
return i > -1;
};
}
}

View File

@ -0,0 +1,21 @@
/*
替换多语言
*/
export default function (editor, str) {
const langArgs = editor.config.langArgs || []
let result = str
langArgs.forEach(item => {
const reg = item.reg
const val = item.val
if (reg.test(result)) {
result = result.replace(reg, function () {
return val
})
}
})
return result
}

View File

@ -0,0 +1,71 @@
/*
工具
*/
// 和 UA 相关的属性
export const UA = {
_ua: navigator.userAgent,
// 是否 webkit
isWebkit: function () {
const reg = /webkit/i
return reg.test(this._ua)
},
// 是否 IE
isIE: function () {
return 'ActiveXObject' in window
}
}
// 遍历对象
export function objForEach(obj, fn) {
let key, result
for (key in obj) {
if (obj.hasOwnProperty(key)) {
result = fn.call(obj, key, obj[key])
if (result === false) {
break
}
}
}
}
// 遍历类数组
export function arrForEach(fakeArr, fn) {
let i, item, result
const length = fakeArr.length || 0
for (i = 0; i < length; i++) {
item = fakeArr[i]
result = fn.call(fakeArr, item, i)
if (result === false) {
break
}
}
}
// 获取随机数
export function getRandom(prefix) {
return prefix + Math.random().toString().slice(2)
}
// 替换 html 特殊字符
export function replaceHtmlSymbol(html) {
if (html == null) {
return ''
}
return html.replace(/</gm, '&lt;')
.replace(/>/gm, '&gt;')
.replace(/"/gm, '&quot;')
}
// 返回百分比的格式
export function percentFormat(number) {
number = (parseInt(number * 100))
return number + '%'
}
// 判断是不是 function
export function isFunction(fn) {
return typeof fn === 'function'
}

View File

@ -0,0 +1,19 @@
.w-e-toolbar,
.w-e-text-container,
.w-e-menu-panel {
padding: 0;
margin: 0;
box-sizing: border-box;
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
}
.w-e-clear-fix:after {
content: "";
display: table;
clear: both;
}

View File

@ -0,0 +1,48 @@
.w-e-toolbar {
.w-e-droplist {
position: absolute;
left: 0;
top: 0;
background-color: #fff;
border: 1px solid #f1f1f1;
border-right-color: #ccc;
border-bottom-color: #ccc;
.w-e-dp-title {
text-align: center;
color: #999;
line-height: 2;
border-bottom: 1px solid #f1f1f1;
font-size: 13px;
}
ul.w-e-list {
list-style: none;
line-height: 1;
li.w-e-item {
color: #333;
padding: 5px 0;
&:hover {
background-color: #f1f1f1;
}
}
}
ul.w-e-block {
list-style: none;
text-align: left;
padding: 5px;
li.w-e-item {
display: inline-block;
padding: 3px 5px;
&:hover {
background-color: #f1f1f1;
}
}
}
}
}

View File

@ -0,0 +1,102 @@
@font-face {
font-family: 'w-e-icon';
src: url('fonts/w-e-icon.woff?ddq1c7') format('truetype');
font-weight: normal;
font-style: normal;
}
[class^="w-e-icon-"], [class*=" w-e-icon-"] {
/* use !important to prevent issues with browser extensions that change fonts */
font-family: 'w-e-icon' !important;
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.w-e-icon-close:before {
content: "\f00d";
}
.w-e-icon-upload2:before {
content: "\e9c6";
}
.w-e-icon-trash-o:before {
content: "\f014";
}
.w-e-icon-header:before {
content: "\f1dc";
}
.w-e-icon-pencil2:before {
content: "\e906";
}
.w-e-icon-paint-brush:before {
content: "\f1fc";
}
.w-e-icon-image:before {
content: "\e90d";
}
.w-e-icon-play:before {
content: "\e912";
}
.w-e-icon-location:before {
content: "\e947";
}
.w-e-icon-undo:before {
content: "\e965";
}
.w-e-icon-redo:before {
content: "\e966";
}
.w-e-icon-quotes-left:before {
content: "\e977";
}
.w-e-icon-list-numbered:before {
content: "\e9b9";
}
.w-e-icon-list2:before {
content: "\e9bb";
}
.w-e-icon-link:before {
content: "\e9cb";
}
.w-e-icon-happy:before {
content: "\e9df";
}
.w-e-icon-bold:before {
content: "\ea62";
}
.w-e-icon-underline:before {
content: "\ea63";
}
.w-e-icon-italic:before {
content: "\ea64";
}
.w-e-icon-strikethrough:before {
content: "\ea65";
}
.w-e-icon-table2:before {
content: "\ea71";
}
.w-e-icon-paragraph-left:before {
content: "\ea77";
}
.w-e-icon-paragraph-center:before {
content: "\ea78";
}
.w-e-icon-paragraph-right:before {
content: "\ea79";
}
.w-e-icon-terminal:before {
content: "\f120";
}
.w-e-icon-page-break:before {
content: "\ea68";
}
.w-e-icon-cancel-circle:before {
content: "\ea0d";
}

View File

@ -0,0 +1,33 @@
.w-e-toolbar {
display: flex;
padding: 0 5px;
/* flex-wrap: wrap; */
/* 单个菜单 */
.w-e-menu {
position: relative;
text-align: center;
padding: 5px 10px;
cursor: pointer;
i {
color: #999;
}
&:hover {
i {
color: #333;
}
}
}
.w-e-active {
i {
color: #1e88e5;
}
&:hover {
i {
color: #1e88e5;
}
}
}
}

View File

@ -0,0 +1,159 @@
.w-e-text-container {
.w-e-panel-container {
position: absolute;
top: 0;
left: 50%;
border: 1px solid #ccc;
border-top: 0;
box-shadow: 1px 1px 2px #ccc;
color: #333;
background-color: #fff;
.w-e-panel-close {
position: absolute;
right: 0;
top: 0;
padding: 5px;
margin: 2px 5px 0 0;
cursor: pointer;
color: #999;
&:hover {
color: #333;
}
}
.w-e-panel-tab-title {
list-style: none;
display: flex;
font-size: 14px;
margin: 2px 10px 0 10px;
border-bottom: 1px solid #f1f1f1;
.w-e-item {
padding: 3px 5px;
color: #999;
cursor: pointer;
margin: 0 3px;
position: relative;
top: 1px;
}
.w-e-active {
color: #333;
border-bottom: 1px solid #333;
cursor: default;
font-weight: 700;
}
}
.w-e-panel-tab-content {
padding: 10px 15px 10px 15px;
font-size: 16px;
/* 输入框的样式 */
input,textarea,button {
&:focus {
outline: none;
}
}
textarea {
width: 100%;
border: 1px solid #ccc;
padding: 5px;
&:focus {
border-color: #1e88e5;
}
}
input[type=text] {
border: none;
border-bottom: 1px solid #ccc;
font-size: 14px;
height: 20px;
color: #333;
text-align: left;
}
input[type=text].small {
width: 30px;
text-align: center;
}
input[type=text].block {
display: block;
width: 100%;
margin: 10px 0;
}
input[type=text]:focus {
border-bottom: 2px solid #1e88e5;
}
/* 按钮的样式 */
.w-e-button-container {
button {
font-size: 14px;
color: #1e88e5;
border: none;
padding: 5px 10px;
background-color: #fff;
cursor: pointer;
border-radius: 3px;
}
button.left {
float: left;
margin-right: 10px;
}
button.right {
float: right;
margin-left: 10px;
}
button.gray {
color: #999;
}
button.red {
color: rgb(194, 79, 74);
}
button:hover {
background-color: #f1f1f1;
}
}
.w-e-button-container:after {
content: "";
display: table;
clear: both;
}
}
/* 为 emotion panel 定制的样式 */
.w-e-emoticon-container {
.w-e-item {
cursor: pointer;
font-size: 18px;
padding: 0 3px;
display: inline-block;
}
}
/* 上传图片的 panel 定制样式 */
.w-e-up-img-container {
text-align: center;
.w-e-up-btn {
display: inline-block;
color: #999;
cursor: pointer;
font-size: 60px;
line-height: 1;
&:hover {
color: #333;
}
}
}
}
}

View File

@ -0,0 +1,77 @@
.w-e-text-container {
position: relative;
.w-e-progress {
position: absolute;
background-color: #1e88e5;
bottom: 0;
left: 0;
height: 1px;
}
}
.w-e-text {
padding: 0 10px;
overflow-y: scroll;
p,h1,h2,h3,h4,h5,table,pre {
margin: 10px 0;
line-height: 1.5;
}
ul, ol {
margin: 10px 0 10px 20px;
}
blockquote {
display: block;
border-left: 8px solid #d0e5f2;
padding: 5px 10px;
margin: 10px 0;
line-height: 1.4;
font-size: 100%;
background-color: #f1f1f1;
}
code {
display: inline-block;
background-color: #f1f1f1;
border-radius: 3px;
padding: 3px 5px;
margin: 0 3px;
}
pre {
code {
display: block;
}
}
table {
border-top: 1px solid #ccc;
border-left: 1px solid #ccc;
td,th {
border-bottom: 1px solid #ccc;
border-right: 1px solid #ccc;
padding: 3px 5px;
}
th {
border-bottom: 2px solid #ccc;
text-align: center;
}
}
&:focus {
outline: none;
}
img {
cursor: pointer;
&:hover {
box-shadow: 0 0 5px #333;
}
}
}