/
Formatter.js
2247 lines (1846 loc) · 67.1 KB
/
Formatter.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
/**
* Formatter.js
*
* Copyright, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
(function(tinymce) {
/**
* Text formatter engine class. This class is used to apply formats like bold, italic, font size
* etc to the current selection or specific nodes. This engine was build to replace the browsers
* default formatting logic for execCommand due to it's inconsistant and buggy behavior.
*
* @class tinymce.Formatter
* @example
* tinymce.activeEditor.formatter.register('mycustomformat', {
* inline : 'span',
* styles : {color : '#ff0000'}
* });
*
* tinymce.activeEditor.formatter.apply('mycustomformat');
*/
/**
* Constructs a new formatter instance.
*
* @constructor Formatter
* @param {tinymce.Editor} ed Editor instance to construct the formatter engine to.
*/
tinymce.Formatter = function(ed) {
var formats = {},
each = tinymce.each,
dom = ed.dom,
selection = ed.selection,
TreeWalker = tinymce.dom.TreeWalker,
rangeUtils = new tinymce.dom.RangeUtils(dom),
isValid = ed.schema.isValidChild,
isBlock = dom.isBlock,
forcedRootBlock = ed.settings.forced_root_block,
nodeIndex = dom.nodeIndex,
INVISIBLE_CHAR = '\uFEFF',
MCE_ATTR_RE = /^(src|href|style)$/,
FALSE = false,
TRUE = true,
formatChangeData,
undef,
getContentEditable = dom.getContentEditable;
function isArray(obj) {
return obj instanceof Array;
};
function getParents(node, selector) {
return dom.getParents(node, selector, dom.getRoot());
};
function isCaretNode(node) {
return node.nodeType === 1 && node.id === '_mce_caret';
};
function defaultFormats() {
register({
alignleft : [
{selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}, defaultBlock: 'div'},
{selector : 'img,table', collapsed : false, styles : {'float' : 'left'}}
],
aligncenter : [
{selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}, defaultBlock: 'div'},
{selector : 'img', collapsed : false, styles : {display : 'block', marginLeft : 'auto', marginRight : 'auto'}},
{selector : 'table', collapsed : false, styles : {marginLeft : 'auto', marginRight : 'auto'}}
],
alignright : [
{selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}, defaultBlock: 'div'},
{selector : 'img,table', collapsed : false, styles : {'float' : 'right'}}
],
alignfull : [
{selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'justify'}, defaultBlock: 'div'}
],
bold : [
{inline : 'strong', remove : 'all'},
{inline : 'span', styles : {fontWeight : 'bold'}},
{inline : 'b', remove : 'all'}
],
italic : [
{inline : 'em', remove : 'all'},
{inline : 'span', styles : {fontStyle : 'italic'}},
{inline : 'i', remove : 'all'}
],
underline : [
{inline : 'span', styles : {textDecoration : 'underline'}, exact : true},
{inline : 'u', remove : 'all'}
],
strikethrough : [
{inline : 'span', styles : {textDecoration : 'line-through'}, exact : true},
{inline : 'strike', remove : 'all'}
],
forecolor : {inline : 'span', styles : {color : '%value'}, wrap_links : false},
hilitecolor : {inline : 'span', styles : {backgroundColor : '%value'}, wrap_links : false},
fontname : {inline : 'span', styles : {fontFamily : '%value'}},
fontsize : {inline : 'span', styles : {fontSize : '%value'}},
fontsize_class : {inline : 'span', attributes : {'class' : '%value'}},
blockquote : {block : 'blockquote', wrapper : 1, remove : 'all'},
subscript : {inline : 'sub'},
superscript : {inline : 'sup'},
link : {inline : 'a', selector : 'a', remove : 'all', split : true, deep : true,
onmatch : function(node) {
return true;
},
onformat : function(elm, fmt, vars) {
each(vars, function(value, key) {
dom.setAttrib(elm, key, value);
});
}
},
removeformat : [
{selector : 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand : true, deep : true},
{selector : 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true},
{selector : '*', attributes : ['style', 'class'], split : false, expand : false, deep : true}
]
});
// Register default block formats
each('p h1 h2 h3 h4 h5 h6 div address pre div code dt dd samp'.split(/\s/), function(name) {
register(name, {block : name, remove : 'all'});
});
// Register user defined formats
register(ed.settings.formats);
};
function addKeyboardShortcuts() {
// Add some inline shortcuts
ed.addShortcut('ctrl+b', 'bold_desc', 'Bold');
ed.addShortcut('ctrl+i', 'italic_desc', 'Italic');
ed.addShortcut('ctrl+u', 'underline_desc', 'Underline');
// BlockFormat shortcuts keys
for (var i = 1; i <= 6; i++) {
ed.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]);
}
ed.addShortcut('ctrl+7', '', ['FormatBlock', false, 'p']);
ed.addShortcut('ctrl+8', '', ['FormatBlock', false, 'div']);
ed.addShortcut('ctrl+9', '', ['FormatBlock', false, 'address']);
};
// Public functions
/**
* Returns the format by name or all formats if no name is specified.
*
* @method get
* @param {String} name Optional name to retrive by.
* @return {Array/Object} Array/Object with all registred formats or a specific format.
*/
function get(name) {
return name ? formats[name] : formats;
};
/**
* Registers a specific format by name.
*
* @method register
* @param {Object/String} name Name of the format for example "bold".
* @param {Object/Array} format Optional format object or array of format variants can only be omitted if the first arg is an object.
*/
function register(name, format) {
if (name) {
if (typeof(name) !== 'string') {
each(name, function(format, name) {
register(name, format);
});
} else {
// Force format into array and add it to internal collection
format = format.length ? format : [format];
each(format, function(format) {
// Set deep to false by default on selector formats this to avoid removing
// alignment on images inside paragraphs when alignment is changed on paragraphs
if (format.deep === undef)
format.deep = !format.selector;
// Default to true
if (format.split === undef)
format.split = !format.selector || format.inline;
// Default to true
if (format.remove === undef && format.selector && !format.inline)
format.remove = 'none';
// Mark format as a mixed format inline + block level
if (format.selector && format.inline) {
format.mixed = true;
format.block_expand = true;
}
// Split classes if needed
if (typeof(format.classes) === 'string')
format.classes = format.classes.split(/\s+/);
});
formats[name] = format;
}
}
};
var getTextDecoration = function(node) {
var decoration;
ed.dom.getParent(node, function(n) {
decoration = ed.dom.getStyle(n, 'text-decoration');
return decoration && decoration !== 'none';
});
return decoration;
};
var processUnderlineAndColor = function(node) {
var textDecoration;
if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) {
textDecoration = getTextDecoration(node.parentNode);
if (ed.dom.getStyle(node, 'color') && textDecoration) {
ed.dom.setStyle(node, 'text-decoration', textDecoration);
} else if (ed.dom.getStyle(node, 'textdecoration') === textDecoration) {
ed.dom.setStyle(node, 'text-decoration', null);
}
}
};
/**
* Applies the specified format to the current selection or specified node.
*
* @method apply
* @param {String} name Name of format to apply.
* @param {Object} vars Optional list of variables to replace within format before applying it.
* @param {Node} node Optional node to apply the format to defaults to current selection.
*/
function apply(name, vars, node) {
var formatList = get(name), format = formatList[0], bookmark, rng, i, isCollapsed = selection.isCollapsed();
function setElementFormat(elm, fmt) {
fmt = fmt || format;
if (elm) {
if (fmt.onformat) {
fmt.onformat(elm, fmt, vars, node);
}
each(fmt.styles, function(value, name) {
dom.setStyle(elm, name, replaceVars(value, vars));
});
each(fmt.attributes, function(value, name) {
dom.setAttrib(elm, name, replaceVars(value, vars));
});
each(fmt.classes, function(value) {
value = replaceVars(value, vars);
if (!dom.hasClass(elm, value))
dom.addClass(elm, value);
});
}
};
function adjustSelectionToVisibleSelection() {
function findSelectionEnd(start, end) {
var walker = new TreeWalker(end);
for (node = walker.current(); node; node = walker.prev()) {
if (node.childNodes.length > 1 || node == start || node.tagName == 'BR') {
return node;
}
}
};
// Adjust selection so that a end container with a end offset of zero is not included in the selection
// as this isn't visible to the user.
var rng = ed.selection.getRng();
var start = rng.startContainer;
var end = rng.endContainer;
if (start != end && rng.endOffset === 0) {
var newEnd = findSelectionEnd(start, end);
var endOffset = newEnd.nodeType == 3 ? newEnd.length : newEnd.childNodes.length;
rng.setEnd(newEnd, endOffset);
}
return rng;
}
function applyStyleToList(node, bookmark, wrapElm, newWrappers, process){
var nodes = [], listIndex = -1, list, startIndex = -1, endIndex = -1, currentWrapElm;
// find the index of the first child list.
each(node.childNodes, function(n, index) {
if (n.nodeName === "UL" || n.nodeName === "OL") {
listIndex = index;
list = n;
return false;
}
});
// get the index of the bookmarks
each(node.childNodes, function(n, index) {
if (n.nodeName === "SPAN" && dom.getAttrib(n, "data-mce-type") == "bookmark") {
if (n.id == bookmark.id + "_start") {
startIndex = index;
} else if (n.id == bookmark.id + "_end") {
endIndex = index;
}
}
});
// if the selection spans across an embedded list, or there isn't an embedded list - handle processing normally
if (listIndex <= 0 || (startIndex < listIndex && endIndex > listIndex)) {
each(tinymce.grep(node.childNodes), process);
return 0;
} else {
currentWrapElm = dom.clone(wrapElm, FALSE);
// create a list of the nodes on the same side of the list as the selection
each(tinymce.grep(node.childNodes), function(n, index) {
if ((startIndex < listIndex && index < listIndex) || (startIndex > listIndex && index > listIndex)) {
nodes.push(n);
n.parentNode.removeChild(n);
}
});
// insert the wrapping element either before or after the list.
if (startIndex < listIndex) {
node.insertBefore(currentWrapElm, list);
} else if (startIndex > listIndex) {
node.insertBefore(currentWrapElm, list.nextSibling);
}
// add the new nodes to the list.
newWrappers.push(currentWrapElm);
each(nodes, function(node) {
currentWrapElm.appendChild(node);
});
return currentWrapElm;
}
};
function applyRngStyle(rng, bookmark, node_specific) {
var newWrappers = [], wrapName, wrapElm, contentEditable = true;
// Setup wrapper element
wrapName = format.inline || format.block;
wrapElm = dom.create(wrapName);
setElementFormat(wrapElm);
rangeUtils.walk(rng, function(nodes) {
var currentWrapElm;
/**
* Process a list of nodes wrap them.
*/
function process(node) {
var nodeName, parentName, found, hasContentEditableState, lastContentEditable;
lastContentEditable = contentEditable;
nodeName = node.nodeName.toLowerCase();
parentName = node.parentNode.nodeName.toLowerCase();
// Node has a contentEditable value
if (node.nodeType === 1 && getContentEditable(node)) {
lastContentEditable = contentEditable;
contentEditable = getContentEditable(node) === "true";
hasContentEditableState = true; // We don't want to wrap the container only it's children
}
// Stop wrapping on br elements
if (isEq(nodeName, 'br')) {
currentWrapElm = 0;
// Remove any br elements when we wrap things
if (format.block)
dom.remove(node);
return;
}
// If node is wrapper type
if (format.wrapper && matchNode(node, name, vars)) {
currentWrapElm = 0;
return;
}
// Can we rename the block
if (contentEditable && !hasContentEditableState && format.block && !format.wrapper && isTextBlock(nodeName)) {
node = dom.rename(node, wrapName);
setElementFormat(node);
newWrappers.push(node);
currentWrapElm = 0;
return;
}
// Handle selector patterns
if (format.selector) {
// Look for matching formats
each(formatList, function(format) {
// Check collapsed state if it exists
if ('collapsed' in format && format.collapsed !== isCollapsed) {
return;
}
if (dom.is(node, format.selector) && !isCaretNode(node)) {
setElementFormat(node, format);
found = true;
}
});
// Continue processing if a selector match wasn't found and a inline element is defined
if (!format.inline || found) {
currentWrapElm = 0;
return;
}
}
// Is it valid to wrap this item
if (contentEditable && !hasContentEditableState && isValid(wrapName, nodeName) && isValid(parentName, wrapName) &&
!(!node_specific && node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279) && !isCaretNode(node)) {
// Start wrapping
if (!currentWrapElm) {
// Wrap the node
currentWrapElm = dom.clone(wrapElm, FALSE);
node.parentNode.insertBefore(currentWrapElm, node);
newWrappers.push(currentWrapElm);
}
currentWrapElm.appendChild(node);
} else if (nodeName == 'li' && bookmark) {
// Start wrapping - if we are in a list node and have a bookmark, then we will always begin by wrapping in a new element.
currentWrapElm = applyStyleToList(node, bookmark, wrapElm, newWrappers, process);
} else {
// Start a new wrapper for possible children
currentWrapElm = 0;
each(tinymce.grep(node.childNodes), process);
if (hasContentEditableState) {
contentEditable = lastContentEditable; // Restore last contentEditable state from stack
}
// End the last wrapper
currentWrapElm = 0;
}
};
// Process siblings from range
each(nodes, process);
});
// Wrap links inside as well, for example color inside a link when the wrapper is around the link
if (format.wrap_links === false) {
each(newWrappers, function(node) {
function process(node) {
var i, currentWrapElm, children;
if (node.nodeName === 'A') {
currentWrapElm = dom.clone(wrapElm, FALSE);
newWrappers.push(currentWrapElm);
children = tinymce.grep(node.childNodes);
for (i = 0; i < children.length; i++)
currentWrapElm.appendChild(children[i]);
node.appendChild(currentWrapElm);
}
each(tinymce.grep(node.childNodes), process);
};
process(node);
});
}
// Cleanup
each(newWrappers, function(node) {
var childCount;
function getChildCount(node) {
var count = 0;
each(node.childNodes, function(node) {
if (!isWhiteSpaceNode(node) && !isBookmarkNode(node))
count++;
});
return count;
};
function mergeStyles(node) {
var child, clone;
each(node.childNodes, function(node) {
if (node.nodeType == 1 && !isBookmarkNode(node) && !isCaretNode(node)) {
child = node;
return FALSE; // break loop
}
});
// If child was found and of the same type as the current node
if (child && matchName(child, format)) {
clone = dom.clone(child, FALSE);
setElementFormat(clone);
dom.replace(clone, node, TRUE);
dom.remove(child, 1);
}
return clone || node;
};
childCount = getChildCount(node);
// Remove empty nodes but only if there is multiple wrappers and they are not block
// elements so never remove single <h1></h1> since that would remove the currrent empty block element where the caret is at
if ((newWrappers.length > 1 || !isBlock(node)) && childCount === 0) {
dom.remove(node, 1);
return;
}
if (format.inline || format.wrapper) {
// Merges the current node with it's children of similar type to reduce the number of elements
if (!format.exact && childCount === 1)
node = mergeStyles(node);
// Remove/merge children
each(formatList, function(format) {
// Merge all children of similar type will move styles from child to parent
// this: <span style="color:red"><b><span style="color:red; font-size:10px">text</span></b></span>
// will become: <span style="color:red"><b><span style="font-size:10px">text</span></b></span>
each(dom.select(format.inline, node), function(child) {
var parent;
// When wrap_links is set to false we don't want
// to remove the format on children within links
if (format.wrap_links === false) {
parent = child.parentNode;
do {
if (parent.nodeName === 'A')
return;
} while (parent = parent.parentNode);
}
removeFormat(format, vars, child, format.exact ? child : null);
});
});
// Remove child if direct parent is of same type
if (matchNode(node.parentNode, name, vars)) {
dom.remove(node, 1);
node = 0;
return TRUE;
}
// Look for parent with similar style format
if (format.merge_with_parents) {
dom.getParent(node.parentNode, function(parent) {
if (matchNode(parent, name, vars)) {
dom.remove(node, 1);
node = 0;
return TRUE;
}
});
}
// Merge next and previous siblings if they are similar <b>text</b><b>text</b> becomes <b>texttext</b>
if (node && format.merge_siblings !== false) {
node = mergeSiblings(getNonWhiteSpaceSibling(node), node);
node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE));
}
}
});
};
if (format) {
if (node) {
if (node.nodeType) {
rng = dom.createRng();
rng.setStartBefore(node);
rng.setEndAfter(node);
applyRngStyle(expandRng(rng, formatList), null, true);
} else {
applyRngStyle(node, null, true);
}
} else {
if (!isCollapsed || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {
// Obtain selection node before selection is unselected by applyRngStyle()
var curSelNode = ed.selection.getNode();
// If the formats have a default block and we can't find a parent block then start wrapping it with a DIV this is for forced_root_blocks: false
// It's kind of a hack but people should be using the default block type P since all desktop editors work that way
if (!forcedRootBlock && formatList[0].defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
apply(formatList[0].defaultBlock);
}
// Apply formatting to selection
ed.selection.setRng(adjustSelectionToVisibleSelection());
bookmark = selection.getBookmark();
applyRngStyle(expandRng(selection.getRng(TRUE), formatList), bookmark);
// Colored nodes should be underlined so that the color of the underline matches the text color.
if (format.styles && (format.styles.color || format.styles.textDecoration)) {
tinymce.walk(curSelNode, processUnderlineAndColor, 'childNodes');
processUnderlineAndColor(curSelNode);
}
selection.moveToBookmark(bookmark);
moveStart(selection.getRng(TRUE));
ed.nodeChanged();
} else
performCaretAction('apply', name, vars);
}
}
};
/**
* Removes the specified format from the current selection or specified node.
*
* @method remove
* @param {String} name Name of format to remove.
* @param {Object} vars Optional list of variables to replace within format before removing it.
* @param {Node/Range} node Optional node or DOM range to remove the format from defaults to current selection.
*/
function remove(name, vars, node) {
var formatList = get(name), format = formatList[0], bookmark, i, rng, contentEditable = true;
// Merges the styles for each node
function process(node) {
var children, i, l, localContentEditable, lastContentEditable, hasContentEditableState;
// Node has a contentEditable value
if (node.nodeType === 1 && getContentEditable(node)) {
lastContentEditable = contentEditable;
contentEditable = getContentEditable(node) === "true";
hasContentEditableState = true; // We don't want to wrap the container only it's children
}
// Grab the children first since the nodelist might be changed
children = tinymce.grep(node.childNodes);
// Process current node
if (contentEditable && !hasContentEditableState) {
for (i = 0, l = formatList.length; i < l; i++) {
if (removeFormat(formatList[i], vars, node, node))
break;
}
}
// Process the children
if (format.deep) {
if (children.length) {
for (i = 0, l = children.length; i < l; i++)
process(children[i]);
if (hasContentEditableState) {
contentEditable = lastContentEditable; // Restore last contentEditable state from stack
}
}
}
};
function findFormatRoot(container) {
var formatRoot;
// Find format root
each(getParents(container.parentNode).reverse(), function(parent) {
var format;
// Find format root element
if (!formatRoot && parent.id != '_start' && parent.id != '_end') {
// Is the node matching the format we are looking for
format = matchNode(parent, name, vars);
if (format && format.split !== false)
formatRoot = parent;
}
});
return formatRoot;
};
function wrapAndSplit(format_root, container, target, split) {
var parent, clone, lastClone, firstClone, i, formatRootParent;
// Format root found then clone formats and split it
if (format_root) {
formatRootParent = format_root.parentNode;
for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) {
clone = dom.clone(parent, FALSE);
for (i = 0; i < formatList.length; i++) {
if (removeFormat(formatList[i], vars, clone, clone)) {
clone = 0;
break;
}
}
// Build wrapper node
if (clone) {
if (lastClone)
clone.appendChild(lastClone);
if (!firstClone)
firstClone = clone;
lastClone = clone;
}
}
// Never split block elements if the format is mixed
if (split && (!format.mixed || !isBlock(format_root)))
container = dom.split(format_root, container);
// Wrap container in cloned formats
if (lastClone) {
target.parentNode.insertBefore(lastClone, target);
firstClone.appendChild(target);
}
}
return container;
};
function splitToFormatRoot(container) {
return wrapAndSplit(findFormatRoot(container), container, container, true);
};
function unwrap(start) {
var node = dom.get(start ? '_start' : '_end'),
out = node[start ? 'firstChild' : 'lastChild'];
// If the end is placed within the start the result will be removed
// So this checks if the out node is a bookmark node if it is it
// checks for another more suitable node
if (isBookmarkNode(out))
out = out[start ? 'firstChild' : 'lastChild'];
dom.remove(node, true);
return out;
};
function removeRngStyle(rng) {
var startContainer, endContainer, node;
rng = expandRng(rng, formatList, TRUE);
if (format.split) {
startContainer = getContainer(rng, TRUE);
endContainer = getContainer(rng);
if (startContainer != endContainer) {
// WebKit will render the table incorrectly if we wrap a TD in a SPAN so lets see if the can use the first child instead
// This will happen if you tripple click a table cell and use remove formatting
if (/^(TR|TD)$/.test(startContainer.nodeName) && startContainer.firstChild) {
startContainer = (startContainer.nodeName == "TD" ? startContainer.firstChild : startContainer.firstChild.firstChild) || startContainer;
}
// Wrap start/end nodes in span element since these might be cloned/moved
startContainer = wrap(startContainer, 'span', {id : '_start', 'data-mce-type' : 'bookmark'});
endContainer = wrap(endContainer, 'span', {id : '_end', 'data-mce-type' : 'bookmark'});
// Split start/end
splitToFormatRoot(startContainer);
splitToFormatRoot(endContainer);
// Unwrap start/end to get real elements again
startContainer = unwrap(TRUE);
endContainer = unwrap();
} else
startContainer = endContainer = splitToFormatRoot(startContainer);
// Update range positions since they might have changed after the split operations
rng.startContainer = startContainer.parentNode;
rng.startOffset = nodeIndex(startContainer);
rng.endContainer = endContainer.parentNode;
rng.endOffset = nodeIndex(endContainer) + 1;
}
// Remove items between start/end
rangeUtils.walk(rng, function(nodes) {
each(nodes, function(node) {
process(node);
// Remove parent span if it only contains text-decoration: underline, yet a parent node is also underlined.
if (node.nodeType === 1 && ed.dom.getStyle(node, 'text-decoration') === 'underline' && node.parentNode && getTextDecoration(node.parentNode) === 'underline') {
removeFormat({'deep': false, 'exact': true, 'inline': 'span', 'styles': {'textDecoration' : 'underline'}}, null, node);
}
});
});
};
// Handle node
if (node) {
if (node.nodeType) {
rng = dom.createRng();
rng.setStartBefore(node);
rng.setEndAfter(node);
removeRngStyle(rng);
} else {
removeRngStyle(node);
}
return;
}
if (!selection.isCollapsed() || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) {
bookmark = selection.getBookmark();
removeRngStyle(selection.getRng(TRUE));
selection.moveToBookmark(bookmark);
// Check if start element still has formatting then we are at: "<b>text|</b>text" and need to move the start into the next text node
if (format.inline && match(name, vars, selection.getStart())) {
moveStart(selection.getRng(true));
}
ed.nodeChanged();
} else
performCaretAction('remove', name, vars);
};
/**
* Toggles the specified format on/off.
*
* @method toggle
* @param {String} name Name of format to apply/remove.
* @param {Object} vars Optional list of variables to replace within format before applying/removing it.
* @param {Node} node Optional node to apply the format to or remove from. Defaults to current selection.
*/
function toggle(name, vars, node) {
var fmt = get(name);
if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle))
remove(name, vars, node);
else
apply(name, vars, node);
};
/**
* Return true/false if the specified node has the specified format.
*
* @method matchNode
* @param {Node} node Node to check the format on.
* @param {String} name Format name to check.
* @param {Object} vars Optional list of variables to replace before checking it.
* @param {Boolean} similar Match format that has similar properties.
* @return {Object} Returns the format object it matches or undefined if it doesn't match.
*/
function matchNode(node, name, vars, similar) {
var formatList = get(name), format, i, classes;
function matchItems(node, format, item_name) {
var key, value, items = format[item_name], i;
// Custom match
if (format.onmatch) {
return format.onmatch(node, format, item_name);
}
// Check all items
if (items) {
// Non indexed object
if (items.length === undef) {
for (key in items) {
if (items.hasOwnProperty(key)) {
if (item_name === 'attributes')
value = dom.getAttrib(node, key);
else
value = getStyle(node, key);
if (similar && !value && !format.exact)
return;
if ((!similar || format.exact) && !isEq(value, replaceVars(items[key], vars)))
return;
}
}
} else {
// Only one match needed for indexed arrays
for (i = 0; i < items.length; i++) {
if (item_name === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(node, items[i]))
return format;
}
}
}
return format;
};
if (formatList && node) {
// Check each format in list
for (i = 0; i < formatList.length; i++) {
format = formatList[i];
// Name name, attributes, styles and classes
if (matchName(node, format) && matchItems(node, format, 'attributes') && matchItems(node, format, 'styles')) {
// Match classes
if (classes = format.classes) {
for (i = 0; i < classes.length; i++) {
if (!dom.hasClass(node, classes[i]))
return;
}
}
return format;
}
}
}
};
/**
* Matches the current selection or specified node against the specified format name.
*
* @method match
* @param {String} name Name of format to match.
* @param {Object} vars Optional list of variables to replace before checking it.
* @param {Node} node Optional node to check.
* @return {boolean} true/false if the specified selection/node matches the format.
*/
function match(name, vars, node) {
var startNode;
function matchParents(node) {
// Find first node with similar format settings
node = dom.getParent(node, function(node) {
return !!matchNode(node, name, vars, true);
});
// Do an exact check on the similar format element
return matchNode(node, name, vars);
};
// Check specified node
if (node)
return matchParents(node);
// Check selected node
node = selection.getNode();
if (matchParents(node))
return TRUE;
// Check start node if it's different
startNode = selection.getStart();
if (startNode != node) {
if (matchParents(startNode))
return TRUE;
}
return FALSE;
};
/**
* Matches the current selection against the array of formats and returns a new array with matching formats.
*
* @method matchAll
* @param {Array} names Name of format to match.
* @param {Object} vars Optional list of variables to replace before checking it.
* @return {Array} Array with matched formats.
*/
function matchAll(names, vars) {
var startElement, matchedFormatNames = [], checkedMap = {}, i, ni, name;
// Check start of selection for formats
startElement = selection.getStart();
dom.getParent(startElement, function(node) {
var i, name;
for (i = 0; i < names.length; i++) {
name = names[i];
if (!checkedMap[name] && matchNode(node, name, vars)) {
checkedMap[name] = true;
matchedFormatNames.push(name);
}
}
}, dom.getRoot());
return matchedFormatNames;