wzp
2021-09-01 2891fe0769189be39c9634b2cbc1841dbd52d022
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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