-
Notifications
You must be signed in to change notification settings - Fork 0
/
editor.js
1876 lines (1778 loc) · 65.5 KB
/
editor.js
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function() {
'use strict';
var _ap = Array.prototype,
_op = Object.prototype,
_fp = Function.prototype,
push = _ap.push,
slice = _ap.slice,
concat = _ap.concat,
toString = _op.toString,
hasOwn = _op.hasOwnProperty,
isArray = Array.isArray,
keys = Object.keys,
//dom functions
buttons = {},
root = this;
var browser = (function() {
// body...
var chrome, firefox, ie, safari, ua;
ua = navigator.userAgent;
ie = /(msie|trident)/i.test(ua);
chrome = /chrome|crios/i.test(ua);
safari = /safari/i.test(ua) && !chrome;
firefox = /firefox/i.test(ua);
if (ie) {
return {
msie: true,
pbr: '',
version: ua.match(/(msie |rv:)(\d+(\.\d+)?)/i)[2] * 1
};
} else if (chrome) {
return {
webkit: true,
chrome: true,
pbr: '<br>',
version: ua.match(/(?:chrome|crios)\/(\d+(\.\d+)?)/i)[1] * 1
};
} else if (safari) {
return {
webkit: true,
safari: true,
pbr: '',
version: ua.match(/version\/(\d+(\.\d+)?)/i)[1] * 1
};
} else if (firefox) {
return {
mozilla: true,
firefox: true,
pbr: '',
version: ua.match(/firefox\/(\d+(\.\d+)?)/i)[1] * 1
};
} else {
return {};
}
})()
browser.createEmptyP = function($parent, $beforeEl, active) {
var cursor = true,
args = slice.call(arguments, 1),
$p = document.createElement("p");
if (args.length === 1) {
if (args[0] === true || args[0] === false) {
cursor = args[0]
}
} else if (args.length === 2){
cursor = args[1]
}
// chrome浏览器中, p元素至少要有一个元素, range才能setStart成功
$p.innerHTML = browser.pbr
if ($beforeEl) {
$parent.insertBefore($p, $beforeEl)
} else {
$parent.appendChild($p)
}
if (cursor) {
var sel = window.getSelection(),
range = sel.getRangeAt(0)
if (!sel || !sel.rangeCount) {
console.log('selection is null or no range!', sel)
return
}
// range设置为$p的第一个节点
range.setStart($p, 0)
// range collapse在开头位置
range.collapse(true);
// range加入到sel中
sel.removeAllRanges();
sel.addRange(range);
}
return $p
}
buttons.register = function(btn) {
if (!btn || !btn.prototype.name) {
console.log("Warning: btn is null or btn.prototype.name is null", btn)
return;
}
if (!buttons[btn.prototype.name]) {
buttons[btn.prototype.name] = btn
}
}
function _extend(source, obj, notReplace) {
for (var prop in source) {
if ((!notReplace) || (notReplace === true && !obj[prop]))
obj[prop] = source[prop]
}
return obj
}
// backbone extend
function extend(child, props) {
var parent = this
// Add static properties to the constructor function, if supplied.
_extend(parent, child);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function() {
this.constructor = child;
};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
if (props) {
_extend(props, child.prototype)
}
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
}
function nodename($el) {
return $el.nodeName.toLowerCase()
}
// 将old element变成new tag, 返回new element
// append: true: append the $nel to it's parent
// false: not append the $nel to it's parent
function transformTo($oel, nTag, append) {
var $child,
$tmp,
$parent = $oel.parentNode,
$nel = document.createElement(nTag)
//console.log("tranformTo:", $parent, $oel, $oel.parentNode)
for ($child = $oel.firstChild; $child !== $oel.lastChild;) {
$tmp = $child.nextSibling
$nel.appendChild($child)
$child = $tmp
}
if ($child) {
$nel.appendChild($child)
}
if (append === true) {
$parent.insertBefore($nel, $oel)
$parent.removeChild($oel)
}
return $nel
}
// $s: start element
// $e: end element
// $c: the final container element: $body
// fn: filter function
// cond: complete condition
function travelUp ($s, $e, $c, fn, cond) {
var $p;
console.log('travelUp: ', $s, $e, $s===$e, $s.nodeType)
for($p = $s.parentNode; $s !== $e && $s !== $c;) {
if (fn($s, $p) === cond) {
console.log(' travel match at:', $s, $p, cond)
return cond
}
$s = $p, $p = $p.parentNode
}
console.log(' travel default:', !cond)
return !cond
}
var Range = function(editor) {
this.sel = window.getSelection ? window.getSelection() : document.getSelection()
this.range = (this.sel && this.sel.rangeCount) ? this.sel.getRangeAt(0) : null
this.editor = editor
this.range !== null ? (this.collapsed = this.range.collapsed) : undefined
}
Range.prototype = {
rangeAtEnd: function(editor) {
if ((!this.range) || (!this.range.collapsed)) {
return false
}
var self = this
return travelUp(self.range.endContainer, editor.$currentEl.parentNode, editor.$body, function($s, $p) {
if ($p) {
if ($s !== $p.lastChild) {
console.log('not last child: ', $s)
return false
}
}
if ($s.nodeType === 3) {
if ($s.length !== self.range.endOffset) {
console.log('not at text end: ', $s)
return false
}
}
return true
}, false)
},
rangeAtStart: function(editor) {
if ((!this.range) || (!this.range.collapsed)) {
return false
}
var self = this
return travelUp(self.range.endContainer, editor.$currentEl.parentNode, editor.$body, function($s, $p) {
if ($p) {
if($s !== $p.firstChild) {
return false
}
}
if ($s.nodeType === 3) {
if (self.range.endOffset !== 0) {
return false
}
}
return true
}, false)
},
clear: function() {
var e;
try {
return this.sel.removeAllRanges();
} catch (_error) {
e = _error;
}
},
// range.collapsed should not handle in this function
// root 应该是editor.$body.parentNode
// 返回所有的叶子节点
getRangeAllNodes: function(root, filterFn) {
if (!this.range) return null;
var start = this.range.startContainer,
end = this.range.endContainer,
result = {
start: null, // 开始的不完整节点
nodes: [], // 中间的完整节点
end: null // 末尾的不完整节点
}
console.log("getRangeAllNodes: ", this.range, this.range.startContainer, start, end)
// 找到最左边的叶子节点
function leafNode(_ele) {
var _child = _ele.firstChild
while(_child) {
_ele = _child
_child = _ele.firstChild
}
return _ele
}
// 查找下一个节点
// 首先,取该节点的nextSibling,如果不为空,取其最左边的叶子节点
// 如果为空, 取其父节点的nextSibling的第一个叶子节点, 如此递归向上,
// 直到到达根节点
function nextNode(_ele) {
while(_ele.parentNode !== root) {
if(_ele.nextSibling) {
var _res = _ele.nextSibling, _child = _res.firstChild
while(_child) {
_res = _child
_child = _child.firstChild
}
return _res
}
_ele = _ele.parentNode
}
// 到达根节点
console.log("Warning: nextNode return null!!!")
return null
}
// start节点和end节点都是叶子节点
//
// 数组中的顺序为:先叶子节点,然后父节点....
function travsel(_start, _end) {
console.log("travsel start:", _start)
console.log("travsel end: ", _end)
//if ((result.end && _start !== result.end.endContainer) || !result.end)
// result.nodes.push(_start)
var _node
for(_node = _start; _node && _node != _end; _node = nextNode(_node)) {
result.nodes.push(_node)
}
}
if (this.range.startContainer === this.range.endContainer ) {
if (!this.range.startContainer.hasChildNodes()) {
result.start = {}
result.start.startContainer = this.range.startContainer
result.start.startOffset = this.range.startOffset
result.start.endContainer = this.range.endContainer
result.start.endOffset = this.range.endOffset
} else {
// 将所有的子节点push到nodes中去
start = leafNode(this.range.startContainer[this.range.startOffset])
end = nextNode(this.range.endContainer[this.range.endOffset - 1])
travsel(start, end)
}
return result
}
// 开始节点与结束节点不同的情况
// 定位开始节点
start = this.range.startContainer
console.log("before compute start node: ", start, this.range.startOffset)
if (start.hasChildNodes()) {
start = leafNode(start.childNodes[this.range.startOffset])
} else {
if (this.range.startOffset !== 0) {
// 开始节点应该不完整的textNode
result.start = {}
result.start.startContainer = result.start.endContainer = start
result.start.startOffset = this.range.startOffset
result.start.endOffset = start.length
// 重新设置开始节点
start = nextNode(this.range.startContainer)
}
}
console.log("compute start node: ", start)
// 定位结束节点
end = this.range.endContainer
console.log("before compute end node: ", end, this.range.endOffset)
if (end.hasChildNodes()) {
end = nextNode(end.childNodes[this.range.endOffset === 0 ? 0 : this.range.endOffset - 1])
} else {
if (this.range.endOffset !== end.length) {
// 结束节点不完整
result.end = {}
result.end.startContainer = result.end.endContainer = end
result.end.startOffset = 0
result.end.endOffset = this.range.endOffset
//end = nextNode(end)
} else {
// 重新设置结束节点
end = nextNode(end)
}
console.log("end node: ", end)
}
console.log("compute end node: ", end)
travsel(start, end)
return result
},
getBodyChild: function($ele) {
var $body = this.editor.$body,
$p
for($p = $ele; $p.parentNode !== $body && $p.parentNode !== document.body; $p = $p.parentNode);
return $p.parentNode === $body ? $p : null
},
getBodyChildren: function() {
var start = this.getBodyChild(this.range.startContainer),
end = this.getBodyChild(this.range.endContainer)
if (start === end) return [start];
var children = []
for (var ele = start; ele !== end; ele = ele.nextSibling) {
children.push(ele)
}
children.push(end)
return children
},
getNodeP: function() {
if (!this.range) return [];
if (this.range.collapsed) {
return this.editor.$currentEl ? [ this.editor.$currentEl ] : []
}
var start = this.getBodyChild(this.range.startContainer),
end = this.getBodyChild(this.range.endContainer);
if (start === null || end === null ) {
throw "start or end is null";
return []
}
if (start === end) return [start];
var children = start.parentNode.childNodes;
var indexStart = _ap.indexOf.call(children, start),
indexEnd = _ap.indexOf.call(children, end)
if (indexStart === -1 || indexEnd === -1) {
throw "start or end is not child of editor body"
}
if (indexStart < indexEnd) {
var tmp = indexEnd
indexStart = tmp
indexEnd = indexStart
}
return _ap.slice.call(children, indexStart, indexEnd+1)
},
doCommand: function(nodetag, fn) {
var nodes,
nd;
if (nodetag === 'p') {
nodes = this.getNodeP()
} else if (nodetag === 'all') {
nodes = this.getRangeAllNodes(this.editor.$body.parentNode)
}
console.log(nodes)
for (var i = 0; i < nodes.length; i++) {
nd = nodes[i];
(nodetag === 'p' && this.editor.$currentEl === nd) ? (this.editor.$currentEl = fn.call(this, nd)) : fn.call(this, nd)
}
},
breakList: function($list, $li, tag) {
var $p,
$el,
$ntagList,
$nList,
$start,
$next,
$insertPos = $list.nextSibling,
liPrev = 0,
liAfter = 0,
converted = false;
if (tag) $ntagList = document.createElement(tag)
for ($start = $list.firstChild; $start; ) {
$next = $start.nextSibling
if ($li === $start) {
if (!tag) {
$p = transformTo($li, 'p')
this.removeChild($list, $li, $p)
$el = $p
} else {
$ntagList.appendChild($li)
$el = $ntagList
}
if (liPrev > 0) {
$list.parentNode.insertBefore($el, $insertPos)
} else {
// 这是第一个li
$list.parentNode.insertBefore($el, $list)
return
}
converted = true
} else {
if (converted) {
if (liAfter === 0) {
$nList = document.createElement($list.nodeName)
}
$nList.appendChild($start)
} else {
liPrev ++;
}
}
$start = $next
}
if (liAfter) {
$list.parentNode.insertBefore($nList, $insertPos)
}
},
// list
// 只有开始元素与结束元素的父节点相同时,才做进一步的处理
//
// 1 range不为collapsed的情况:
// 从当前元素开始处理,直到该元素的同级元素处理完,向上处理,直到range的end元素及end branch元素
//
convertToList: function(ntag) {
var $start,
tag,
$first,
$last,
$next,
$insertPos,
$nList,
$li,
$parent;
if (!this.range) return;
$first = this.editor.travelUntilTags(this.range.startContainer, ['p', 'li'])
$last = this.editor.travelUntilTags(this.range.endContainer, ['p', 'li'])
$parent = $first.parentNode
if (this.collapsed) {
tag = nodename($parent)
$nList = document.createElement(ntag)
this.save()
if (tag === 'ol' || tag === 'ul') {
// break list
this.breakList($first.parentNode, $first, tag === ntag ? null : ntag)
} else if (nodename($first) === 'p'){
$li = transformTo($first, 'li', false)
$nList.appendChild($li)
$parent.insertBefore($nList, $first)
this.removeChild($parent, $first, $li)
}
this.restore()
return
}
// 如果选中的是一整个ul或ol, 将对整个这个元素进行变换
tag = nodename($parent)
if ((tag === 'ul' || tag === 'ol') && $first.parentNode === $last.parentNode
&& $first === $parent.firstChild && $last === $parent.lastChild) {
var $p,
$ancient = $parent.parentNode
this.save()
if (tag === ntag) {
// 移除parent, 变成p
$insertPos = $parent.nextSibling
for ($start = $first; $start; ) {
$next = $start.nextSibling
$p = transformTo($start, 'p')
$ancient.insertBefore($p, $insertPos)
$start = $next
}
$ancient.removeChild($parent)
} else {
// 变成ntag
$nList = transformTo($parent, ntag, true)
}
this.restore()
return
}
// 将所有选中的元素,尽最大的可能合并为一个list
// 如果选中开始元素是父元素的第一个元素,且选中元素为li,或父元素为blockquote,则选中区域上升为其父节点
if ( $first === $parent.firstChild ) {
(nodename($first) === 'li' || nodename($parent) === 'blockquote') && ($first = $parent);
}
$parent = $last.parentNode
if ($last === $parent.lastChild) {
(nodename($last) === 'li' || nodename($parent) === 'blockquote') && ($last = $parent);
}
if ($first.parentNode !== $last.parentNode) {
console.log("start node position not same with end node position, not handle it.", $first, $last)
return
}
$nList = document.createElement(ntag)
$parent = $first.parentNode
$insertPos = $last.nextSibling
var childCount = 0
this.save()
for ($start = $first; $start != $insertPos; ) {
tag = nodename($start)
$next = $start.nextSibling
if (tag === 'p') {
$li = transformTo($start, 'li', false)
$nList.appendChild($li)
this.removeChild($parent, $start, $li)
childCount ++
} else if (tag === 'ol' || tag === 'ul') {
var $child,
$nextChild
for ($child = $start.firstChild; $child; ) {
$nextChild = $child.nextSibling
$nList.appendChild($child)
childCount ++
$child = $child.nextSibling
}
this.removeChild($parent, $start, $li)
} else {
if (childCount > 0) {
// close the list, create a new list
$parent.insertBefore($nList, $start)
$nList = document.createElement(ntag)
childCount = 0
}
}
$start = $next
}
if (childCount) {
$parent.insertBefore($nList, $insertPos)
} else {
//document.removeChild($nList)
}
this.restore()
},
// 将blockquote的子元素元素变为list
convertQuoteToList: function($quote, ntag) {
var $nList = document.createElement(ntag)
// quote下的元素为已经是ntag,且只有这一个元素,移除该list
if (nodename($quote.firstChild) === ntag && $quote.firstChild === $quote.lastChild) {
var $list = $quote.firstChild,
$el,
$next
for ($el = $list.firstChild; $el; ) {
$next = $el.nextSibling
$nList.appendChild($el)
$el = $next
}
$quote.removeChild($quote.firstChild)
$quote.appendChild($nList)
}
},
// call this function, the range.save() should be called before
// after range.save
removeChild: function(parent, child, nchild, startOffset, endOffset) {
if (this._start && this._start === child) {
this._start = nchild;
(startOffset !== undefined) && (this._startOffset = startOffset);
console.log("reset startContainer to ", nchild, " , startOffset to ", startOffset)
}
if (this._end && this._end === child) {
this._end = nchild;
endOffset && (this._endOffset = endOffset);
console.log("reset endContainer to ", nchild, " , endOffset to ", endOffset)
}
parent.removeChild(child)
},
setStart: function (_start, _offset) {
_start && (this._start = _start);
_offset && (this._startOffset = _offset);
},
setEnd: function(_end, _offset) {
_end && (this._end = _end)
_offset && (this._endOffset = _offset)
},
save: function() {
if (!this.range) {
throw "range.save: this.range is null!!!"
return
};
if (this._start) return;
this._start = this.range.startContainer
this._startOffset = this.range.startOffset
this._end = this.range.endContainer
this._endOffset = this.range.endOffset
console.log("range save: ", this._startOffset, this._endOffset)
return this
},
restore: function(or) {
var rg = or ? or : this
console.log("restore: ", rg._start,rg._startOffset, rg._end, rg._endOffset)
this.clear()
var range = document.createRange();
range.setStart(rg._start, rg._startOffset);
range.setEnd(rg._end, rg._endOffset);
this.sel.addRange(range);
return this
}
}
var Event = {
on: function(name, cb, ctx) {
this.events || (this.events = {});
(this.events[name] || (this.events[name] = [])).push({
cb: cb,
ctx: ctx
})
return this
},
off: function(name, fn, ctx) {
if (!this.events) {
return this
}
if (!arguments.length) {
this.events = void 0
return this
}
var events = this.events[name]
if (!events) {
return this
}
if (arguments.length === 1){
delete this.events[name]
return this
}
var cb
for (var i =0; i < events.length; i ++) {
cb = events[i]
if (cb.cb === fn && cb.ctx === ctx) {
events.splice(i, 1)
break
}
}
return this
},
fire: function(name, a, b, c) {
if (!this.events) return this;
var events = this.events[name]
if (events) {
var event
for (var i = 0; i < events.length; i ++) {
event = events[i]
event.cb.call(event.ctx, name, a, b, c)
}
}
return this
}
}
/**
* Button
*
*
*/
var Button = function(argument) {
var arg = argument || {}
var btn = function() {
this.status = arg.status || ''
// on init, set the $button element
this.$el = null
this.$a = null
this.$exclueBtns = []
}
return btn
}
Button.prototype = {
init: function(editor) {
var self = this,
$li = document.createElement('li')
if (typeof this.command === 'string' && this.command) {
$li.setAttribute('data-cmd', this.command)
}
if (this.tag) {
$li.setAttribute('data-tag', this.tag)
}
$li.addEventListener('click', function(event) {self.onclick.call(self, event)})
// render button
$li.innerHTML = '<a tabindex="-1" unselectable="on" class="toolbar-item toolbar-item-' +
this.name + '" class="active: false" href="javascript:;" title="' +
this.title +
'"><span class="' +
this.icon +
'"></span></a>'
this.$el = $li
this.$a = $li.firstChild
// set editor
this.editor = editor
if(this.typ === 'menu') {
this.renderMenu()
}
},
renderMenu: function() {
if (! isArray(this.menus)) {
console.log('this.menus is NOT Array!')
return
}
var menu,
$menuWrapper = document.createElement('div'),
$ul = document.createElement('ul'),
$menuItem,
$a,
$span;
$menuWrapper.setAttribute('class', 'toolbar-menu')
$menuWrapper.classList.add('toolbar-menu'+this.name)
for (var i = 0; i < this.menus.length; i ++) {
menu = this.menus[i]
$menuItem = document.createElement('li')
if (menu === '|') {
$menuItem.innerHTML = '<span class="separator"></span>'
$ul.appendChild($menuItem)
continue
}
$span = document.createElement('span')
$a = document.createElement('a')
$span.innerText = menu.text || ''
$a.appendChild($span)
$a.classList.add('menu-item')
$a.classList.add("menu-item"+ (menu.param||''))
$a.setAttribute('tabindex', -1)
$a.setAttribute('title', menu.text || '')
$a.href = "javascript:;"
$menuItem.setAttribute('data-param', menu.param || '')
$menuItem.appendChild($a)
$ul.appendChild($menuItem)
}
$menuWrapper.appendChild($ul)
this.$el.appendChild($menuWrapper)
},
liClicked: function (event) {
var $el
for ($el = event.target; $el !== this.$li; $el = $el.parentNode ) {
if ($el.nodeName.toLowerCase() === 'li') {
break
}
}
return $el
},
onclick: function(event) {
this.editor.resetStatus()
if (this.typ === 'menu') {
var $el = this.liClicked(event)
if ($el === this.$el) {
this.$el.classList.toggle('menu-on')
} else {
// hide menu
this.$el.classList.remove('menu-on')
// exec the command
if (this.execMenuCmd) {
var cmd = $el.getAttribute('data-param')
this.range = new Range(this.editor)
this.range.save()
this.execMenuCmd(event, cmd)
this.range.restore()
}
}
} else if (this.typ === 'basic') {
this.command && document.execCommand(this.command, false)
this.editor.fire('statusChange')
this.updateStatus(event)
} else {
this.exec(event)
this.editor.fire('statusChange')
}
this.editor.$body.focus()
event.preventDefault()
event.stopPropagation()
return false
},
exec: function(event) { },
// if active, set exclude button to disable
// if not active, remove exclude button's disable.
toggleExclude: function(active) {
var i, exButton
for (i = 0; i < this.editor.$buttons.length; i ++) {
exButton = this.editor.$buttons[i]
if (exButton.typ === 'basic') {
document.queryCommandState(exButton.command) ? exButton.$a.classList.add('active') : exButton.$a.classList.remove('active');
} else {
exButton.$a.classList.contains('disabled') && exButton.$a.classList.remove('disabled')
}
}
if (!this.$exclueBtns) return;
console.log('toggle exclude: ', this.name, this.$exclueBtns)
for (i = 0; i < this.$exclueBtns.length; i ++) {
exButton = this.$exclueBtns[i]
if (active) {
exButton.$a.classList.add('disabled')
} else {
exButton.$a.classList.remove('disabled')
}
}
},
updateStatus: function(event) {
if (this.typ === 'basic') {
if (document.queryCommandState(this.command)) {
this.$a.classList.add('active')
this.toggleExclude(true)
}
} else {
console.log(this.name, ' update status ', this.editor.$currentEl, nodename(this.editor.$currentEl))
if (nodename(this.editor.$currentEl) === this.name) {
this.$a.classList.add('active')
this.toggleExclude(true)
} else {
this.$a.classList.remove('active')
this.toggleExclude(false)
}
}
}
}
_extend(Event, Button.prototype)
Button.extend = function(fn, props) {
var btn = extend.call(this, fn, props)
buttons.register(btn)
return btn
}
var TextButton = Button.extend(Button(), {
name: 'title',
title: '标题文字',
icon: 'fa fa-text',
tag: 'title',
command: '',
status: '',
typ: 'menu',
menus:[{
name: 'normal',
text: '普通文本',
param: 'p'
}, '|', {
name: 'h1',
text: '标题 1',
param: 'h1'
}, {
name: 'h2',
text: '标题 2',
param: 'h2'
}, {
name: 'h3',
text: '标题 3',
param: 'h3'
}],
exclueButtons: []
})
TextButton.prototype.execMenuCmd = function(event, cmd) {
var range = this.range
range.save()
range.doCommand('p', function($el) {
var tag = $el.nodeName
if (tag === cmd) return $el;
return transformTo($el, cmd, true)
})
range.restore()
}
TextButton.prototype.setActive = function(cls) {
if (cls === '') {
this.$a.classList.remove('active')
this.$a.classList.remove('active-h1')
this.$a.classList.remove('active-h2')
this.$a.classList.remove('active-h3')
return
}
this.$a.classList.add('active')
if (cls === 'h1') {
this.$a.classList.remove('active-h2')
this.$a.classList.remove('active-h3')
this.$a.classList.add('active-h1')
} else if (cls === 'h2'){
this.$a.classList.remove('active-h1')
this.$a.classList.remove('active-h3')
this.$a.classList.add('active-h2')
} else if (cls === 'h3'){
this.$a.classList.remove('active-h1')
this.$a.classList.remove('active-h2')
this.$a.classList.add('active-h3')
}
}
TextButton.prototype.updateStatus = function(event) {
var editor = this.editor,
tagName
if (!editor.$currentEl) return;
tagName = editor.$currentEl.nodeName.toLowerCase()
console.log('text button update status: ',editor.$currentEl, tagName)
if (tagName === 'h1') {
this.setActive('h1')
} else if (tagName === 'h2') {
this.setActive('h2')
} else if (tagName === 'h3') {
this.setActive('h3')
} else {
this.setActive('')
}
}
// bold button
var BoldButton = Button.extend(Button(), {
name: 'bold',
icon: 'fa fa-bold',
title: '加粗文字 ( Ctrl + b )',
tag: 'b',
typ: 'basic',
command: 'bold',
excludeButtons: []
})
// italic button
var ItalicButton = Button.extend(Button(), {
name: 'italic',
icon: 'fa fa-italic',
title: '斜体文字 ( Ctrl + i )',
tag: 'i',
typ: 'basic',
command: 'italic',
menu: false,
excludeButtons: []
})
// underline button
var UnderlineButton = Button.extend(Button(), {
name: 'underline',
icon: 'fa fa-underline',
title: '下划线文字 ( Ctrl + u )',
tag: 'u',
typ: 'basic',
command: 'underline',
menu: false,
excludeButtons: []
})
// strike button
var StrikeButton = Button.extend(Button(), {
name: 'strike',
icon: 'fa fa-strikethrough',
title: '下划线文字 ( Ctrl + u )',
tag: 'strike',
typ: 'basic',
command: 'strikethrough',