Quirks.js
51 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
/**
* Quirks.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*
* @ignore-file
*/
/**
* This file includes fixes for various browser quirks it's made to make it easy to add/remove browser specific fixes.
*
* @private
* @class tinymce.util.Quirks
*/
define("tinymce/util/Quirks", [
"tinymce/util/VK",
"tinymce/dom/RangeUtils",
"tinymce/dom/TreeWalker",
"tinymce/dom/NodePath",
"tinymce/html/Node",
"tinymce/html/Entities",
"tinymce/Env",
"tinymce/util/Tools",
"tinymce/util/Delay",
"tinymce/caret/CaretContainer",
"tinymce/caret/CaretPosition",
"tinymce/caret/CaretWalker"
], function(VK, RangeUtils, TreeWalker, NodePath, Node, Entities, Env, Tools, Delay, CaretContainer, CaretPosition, CaretWalker) {
return function(editor) {
var each = Tools.each, $ = editor.$;
var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection,
settings = editor.settings, parser = editor.parser, serializer = editor.serializer;
var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
var mceInternalUrlPrefix = 'data:text/mce-internal,';
var mceInternalDataType = isIE ? 'Text' : 'URL';
/**
* Executes a command with a specific state this can be to enable/disable browser editing features.
*/
function setEditorCommandState(cmd, state) {
try {
editor.getDoc().execCommand(cmd, false, state);
} catch (ex) {
// Ignore
}
}
/**
* Returns current IE document mode.
*/
function getDocumentMode() {
var documentMode = editor.getDoc().documentMode;
return documentMode ? documentMode : 6;
}
/**
* Returns true/false if the event is prevented or not.
*
* @private
* @param {Event} e Event object.
* @return {Boolean} true/false if the event is prevented or not.
*/
function isDefaultPrevented(e) {
return e.isDefaultPrevented();
}
/**
* Sets Text/URL data on the event's dataTransfer object to a special data:text/mce-internal url.
* This is to workaround the inability to set custom contentType on IE and Safari.
* The editor's selected content is encoded into this url so drag and drop between editors will work.
*
* @private
* @param {DragEvent} e Event object
*/
function setMceInternalContent(e) {
var selectionHtml, internalContent;
if (e.dataTransfer) {
if (editor.selection.isCollapsed() && e.target.tagName == 'IMG') {
selection.select(e.target);
}
selectionHtml = editor.selection.getContent();
// Safari/IE doesn't support custom dataTransfer items so we can only use URL and Text
if (selectionHtml.length > 0) {
internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml);
e.dataTransfer.setData(mceInternalDataType, internalContent);
}
}
}
/**
* Gets content of special data:text/mce-internal url on the event's dataTransfer object.
* This is to workaround the inability to set custom contentType on IE and Safari.
* The editor's selected content is encoded into this url so drag and drop between editors will work.
*
* @private
* @param {DragEvent} e Event object
* @returns {String} mce-internal content
*/
function getMceInternalContent(e) {
var internalContent;
if (e.dataTransfer) {
internalContent = e.dataTransfer.getData(mceInternalDataType);
if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) {
internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(',');
return {
id: unescape(internalContent[0]),
html: unescape(internalContent[1])
};
}
}
return null;
}
/**
* Inserts contents using the paste clipboard command if it's available if it isn't it will fallback
* to the core command.
*
* @private
* @param {String} content Content to insert at selection.
*/
function insertClipboardContents(content) {
if (editor.queryCommandSupported('mceInsertClipboardContent')) {
editor.execCommand('mceInsertClipboardContent', false, {content: content});
} else {
editor.execCommand('mceInsertContent', false, content);
}
}
/**
* Fixes a WebKit bug when deleting contents using backspace or delete key.
* WebKit will produce a span element if you delete across two block elements.
*
* Example:
* <h1>a</h1><p>|b</p>
*
* Will produce this on backspace:
* <h1>a<span style="<all runtime styles>">b</span></p>
*
* This fixes the backspace to produce:
* <h1>a|b</p>
*
* See bug: https://bugs.webkit.org/show_bug.cgi?id=45784
*
* This fixes the following delete scenarios:
* 1. Delete by pressing backspace key.
* 2. Delete by pressing delete key.
* 3. Delete by pressing backspace key with ctrl/cmd (Word delete).
* 4. Delete by pressing delete key with ctrl/cmd (Word delete).
* 5. Delete by drag/dropping contents inside the editor.
* 6. Delete by using Cut Ctrl+X/Cmd+X.
* 7. Delete by selecting contents and writing a character.
*
* This code is a ugly hack since writing full custom delete logic for just this bug
* fix seemed like a huge task. I hope we can remove this before the year 2030.
*/
function cleanupStylesWhenDeleting() {
var doc = editor.getDoc(), dom = editor.dom, selection = editor.selection;
var MutationObserver = window.MutationObserver, olderWebKit, dragStartRng;
// Add mini polyfill for older WebKits
// TODO: Remove this when old Safari versions gets updated
if (!MutationObserver) {
olderWebKit = true;
MutationObserver = function() {
var records = [], target;
function nodeInsert(e) {
var target = e.relatedNode || e.target;
records.push({target: target, addedNodes: [target]});
}
function attrModified(e) {
var target = e.relatedNode || e.target;
records.push({target: target, attributeName: e.attrName});
}
this.observe = function(node) {
target = node;
target.addEventListener('DOMSubtreeModified', nodeInsert, false);
target.addEventListener('DOMNodeInsertedIntoDocument', nodeInsert, false);
target.addEventListener('DOMNodeInserted', nodeInsert, false);
target.addEventListener('DOMAttrModified', attrModified, false);
};
this.disconnect = function() {
target.removeEventListener('DOMSubtreeModified', nodeInsert, false);
target.removeEventListener('DOMNodeInsertedIntoDocument', nodeInsert, false);
target.removeEventListener('DOMNodeInserted', nodeInsert, false);
target.removeEventListener('DOMAttrModified', attrModified, false);
};
this.takeRecords = function() {
return records;
};
};
}
function isTrailingBr(node) {
var blockElements = dom.schema.getBlockElements(), rootNode = editor.getBody();
if (node.nodeName != 'BR') {
return false;
}
for (; node != rootNode && !blockElements[node.nodeName]; node = node.parentNode) {
if (node.nextSibling) {
return false;
}
}
return true;
}
function isSiblingsIgnoreWhiteSpace(node1, node2) {
var node;
for (node = node1.nextSibling; node && node != node2; node = node.nextSibling) {
if (node.nodeType == 3 && $.trim(node.data).length === 0) {
continue;
}
if (node !== node2) {
return false;
}
}
return node === node2;
}
function findCaretNode(node, forward, startNode) {
var walker, current, nonEmptyElements;
nonEmptyElements = dom.schema.getNonEmptyElements();
walker = new TreeWalker(startNode || node, node);
while ((current = walker[forward ? 'next' : 'prev']())) {
if (nonEmptyElements[current.nodeName] && !isTrailingBr(current)) {
return current;
}
if (current.nodeType == 3 && current.data.length > 0) {
return current;
}
}
}
function deleteRangeBetweenTextBlocks(rng) {
var startBlock, endBlock, caretNodeBefore, caretNodeAfter, textBlockElements;
if (rng.collapsed) {
return;
}
startBlock = dom.getParent(RangeUtils.getNode(rng.startContainer, rng.startOffset), dom.isBlock);
endBlock = dom.getParent(RangeUtils.getNode(rng.endContainer, rng.endOffset), dom.isBlock);
textBlockElements = editor.schema.getTextBlockElements();
if (startBlock == endBlock) {
return;
}
if (!textBlockElements[startBlock.nodeName] || !textBlockElements[endBlock.nodeName]) {
return;
}
if (dom.getContentEditable(startBlock) === "false" || dom.getContentEditable(endBlock) === "false") {
return;
}
rng.deleteContents();
caretNodeBefore = findCaretNode(startBlock, false);
caretNodeAfter = findCaretNode(endBlock, true);
if (!dom.isEmpty(endBlock)) {
$(startBlock).append(endBlock.childNodes);
}
$(endBlock).remove();
if (caretNodeBefore) {
if (caretNodeBefore.nodeType == 1) {
if (caretNodeBefore.nodeName == "BR") {
rng.setStartBefore(caretNodeBefore);
rng.setEndBefore(caretNodeBefore);
} else {
rng.setStartAfter(caretNodeBefore);
rng.setEndAfter(caretNodeBefore);
}
} else {
rng.setStart(caretNodeBefore, caretNodeBefore.data.length);
rng.setEnd(caretNodeBefore, caretNodeBefore.data.length);
}
} else if (caretNodeAfter) {
if (caretNodeAfter.nodeType == 1) {
rng.setStartBefore(caretNodeAfter);
rng.setEndBefore(caretNodeAfter);
} else {
rng.setStart(caretNodeAfter, 0);
rng.setEnd(caretNodeAfter, 0);
}
}
selection.setRng(rng);
return true;
}
function expandBetweenBlocks(rng, isForward) {
var caretNode, targetCaretNode, textBlock, targetTextBlock, container, offset;
if (!rng.collapsed) {
return rng;
}
container = rng.startContainer;
offset = rng.startOffset;
if (container.nodeType == 3) {
if (isForward) {
if (offset < container.data.length) {
return rng;
}
} else {
if (offset > 0) {
return rng;
}
}
}
caretNode = RangeUtils.getNode(rng.startContainer, rng.startOffset);
textBlock = dom.getParent(caretNode, dom.isBlock);
targetCaretNode = findCaretNode(editor.getBody(), isForward, caretNode);
targetTextBlock = dom.getParent(targetCaretNode, dom.isBlock);
if (!caretNode || !targetCaretNode) {
return rng;
}
if (targetTextBlock && textBlock != targetTextBlock) {
if (!isForward) {
if (!isSiblingsIgnoreWhiteSpace(targetTextBlock, textBlock)) {
return rng;
}
if (targetCaretNode.nodeType == 1) {
if (targetCaretNode.nodeName == "BR") {
rng.setStartBefore(targetCaretNode);
} else {
rng.setStartAfter(targetCaretNode);
}
} else {
rng.setStart(targetCaretNode, targetCaretNode.data.length);
}
if (caretNode.nodeType == 1) {
rng.setEnd(caretNode, 0);
} else {
rng.setEndBefore(caretNode);
}
} else {
if (!isSiblingsIgnoreWhiteSpace(textBlock, targetTextBlock)) {
return rng;
}
if (caretNode.nodeType == 1) {
if (caretNode.nodeName == "BR") {
rng.setStartBefore(caretNode);
} else {
rng.setStartAfter(caretNode);
}
} else {
rng.setStart(caretNode, caretNode.data.length);
}
if (targetCaretNode.nodeType == 1) {
rng.setEnd(targetCaretNode, 0);
} else {
rng.setEndBefore(targetCaretNode);
}
}
}
return rng;
}
function handleTextBlockMergeDelete(isForward) {
var rng = selection.getRng();
rng = expandBetweenBlocks(rng, isForward);
if (deleteRangeBetweenTextBlocks(rng)) {
return true;
}
}
/**
* This retains the formatting if the last character is to be deleted.
*
* Backspace on this: <p><b><i>a|</i></b></p> would become <p>|</p> in WebKit.
* With this patch: <p><b><i>|<br></i></b></p>
*/
function handleLastBlockCharacterDelete(isForward, rng) {
var path, blockElm, newBlockElm, clonedBlockElm, sibling,
container, offset, br, currentFormatNodes;
function cloneTextBlockWithFormats(blockElm, node) {
currentFormatNodes = $(node).parents().filter(function(idx, node) {
return !!editor.schema.getTextInlineElements()[node.nodeName];
});
newBlockElm = blockElm.cloneNode(false);
currentFormatNodes = Tools.map(currentFormatNodes, function(formatNode) {
formatNode = formatNode.cloneNode(false);
if (newBlockElm.hasChildNodes()) {
formatNode.appendChild(newBlockElm.firstChild);
newBlockElm.appendChild(formatNode);
} else {
newBlockElm.appendChild(formatNode);
}
newBlockElm.appendChild(formatNode);
return formatNode;
});
if (currentFormatNodes.length) {
br = dom.create('br');
currentFormatNodes[0].appendChild(br);
dom.replace(newBlockElm, blockElm);
rng.setStartBefore(br);
rng.setEndBefore(br);
editor.selection.setRng(rng);
return br;
}
return null;
}
function isTextBlock(node) {
return node && editor.schema.getTextBlockElements()[node.tagName];
}
if (!rng.collapsed) {
return;
}
container = rng.startContainer;
offset = rng.startOffset;
blockElm = dom.getParent(container, dom.isBlock);
if (!isTextBlock(blockElm)) {
return;
}
if (container.nodeType == 1) {
container = container.childNodes[offset];
if (container && container.tagName != 'BR') {
return;
}
if (isForward) {
sibling = blockElm.nextSibling;
} else {
sibling = blockElm.previousSibling;
}
if (dom.isEmpty(blockElm) && isTextBlock(sibling) && dom.isEmpty(sibling)) {
if (cloneTextBlockWithFormats(blockElm, container)) {
dom.remove(sibling);
return true;
}
}
} else if (container.nodeType == 3) {
path = NodePath.create(blockElm, container);
clonedBlockElm = blockElm.cloneNode(true);
container = NodePath.resolve(clonedBlockElm, path);
if (isForward) {
if (offset >= container.data.length) {
return;
}
container.deleteData(offset, 1);
} else {
if (offset <= 0) {
return;
}
container.deleteData(offset - 1, 1);
}
if (dom.isEmpty(clonedBlockElm)) {
return cloneTextBlockWithFormats(blockElm, container);
}
}
}
function customDelete(isForward) {
var mutationObserver, rng, caretElement;
if (handleTextBlockMergeDelete(isForward)) {
return;
}
Tools.each(editor.getBody().getElementsByTagName('*'), function(elm) {
// Mark existing spans
if (elm.tagName == 'SPAN') {
elm.setAttribute('mce-data-marked', 1);
}
// Make sure all elements has a data-mce-style attribute
if (!elm.hasAttribute('data-mce-style') && elm.hasAttribute('style')) {
editor.dom.setAttrib(elm, 'style', editor.dom.getAttrib(elm, 'style'));
}
});
// Observe added nodes and style attribute changes
mutationObserver = new MutationObserver(function() {});
mutationObserver.observe(editor.getDoc(), {
childList: true,
attributes: true,
subtree: true,
attributeFilter: ['style']
});
editor.getDoc().execCommand(isForward ? 'ForwardDelete' : 'Delete', false, null);
rng = editor.selection.getRng();
caretElement = rng.startContainer.parentNode;
Tools.each(mutationObserver.takeRecords(), function(record) {
if (!dom.isChildOf(record.target, editor.getBody())) {
return;
}
// Restore style attribute to previous value
if (record.attributeName == "style") {
var oldValue = record.target.getAttribute('data-mce-style');
if (oldValue) {
record.target.setAttribute("style", oldValue);
} else {
record.target.removeAttribute("style");
}
}
// Remove all spans that aren't marked and retain selection
Tools.each(record.addedNodes, function(node) {
if (node.nodeName == "SPAN" && !node.getAttribute('mce-data-marked')) {
var offset, container;
if (node == caretElement) {
offset = rng.startOffset;
container = node.firstChild;
}
dom.remove(node, true);
if (container) {
rng.setStart(container, offset);
rng.setEnd(container, offset);
editor.selection.setRng(rng);
}
}
});
});
mutationObserver.disconnect();
// Remove any left over marks
Tools.each(editor.dom.select('span[mce-data-marked]'), function(span) {
span.removeAttribute('mce-data-marked');
});
}
editor.on('keydown', function(e) {
var isForward = e.keyCode == DELETE, isMetaOrCtrl = e.ctrlKey || e.metaKey;
if (!isDefaultPrevented(e) && (isForward || e.keyCode == BACKSPACE)) {
var rng = editor.selection.getRng(), container = rng.startContainer, offset = rng.startOffset;
// Shift+Delete is cut
if (isForward && e.shiftKey) {
return;
}
if (handleLastBlockCharacterDelete(isForward, rng)) {
e.preventDefault();
return;
}
// Ignore non meta delete in the where there is text before/after the caret
if (!isMetaOrCtrl && rng.collapsed && container.nodeType == 3) {
if (isForward ? offset < container.data.length : offset > 0) {
return;
}
}
e.preventDefault();
if (isMetaOrCtrl) {
editor.selection.getSel().modify("extend", isForward ? "forward" : "backward", e.metaKey ? "lineboundary" : "word");
}
customDelete(isForward);
}
});
// Handle case where text is deleted by typing over
editor.on('keypress', function(e) {
if (!isDefaultPrevented(e) && !selection.isCollapsed() && e.charCode > 31 && !VK.metaKeyPressed(e)) {
var rng, currentFormatNodes, fragmentNode, blockParent, caretNode, charText;
rng = editor.selection.getRng();
charText = String.fromCharCode(e.charCode);
e.preventDefault();
// Keep track of current format nodes
currentFormatNodes = $(rng.startContainer).parents().filter(function(idx, node) {
return !!editor.schema.getTextInlineElements()[node.nodeName];
});
customDelete(true);
// Check if the browser removed them
currentFormatNodes = currentFormatNodes.filter(function(idx, node) {
return !$.contains(editor.getBody(), node);
});
// Then re-add them
if (currentFormatNodes.length) {
fragmentNode = dom.createFragment();
currentFormatNodes.each(function(idx, formatNode) {
formatNode = formatNode.cloneNode(false);
if (fragmentNode.hasChildNodes()) {
formatNode.appendChild(fragmentNode.firstChild);
fragmentNode.appendChild(formatNode);
} else {
caretNode = formatNode;
fragmentNode.appendChild(formatNode);
}
fragmentNode.appendChild(formatNode);
});
caretNode.appendChild(editor.getDoc().createTextNode(charText));
// Prevent edge case where older WebKit would add an extra BR element
blockParent = dom.getParent(rng.startContainer, dom.isBlock);
if (dom.isEmpty(blockParent)) {
$(blockParent).empty().append(fragmentNode);
} else {
rng.insertNode(fragmentNode);
}
rng.setStart(caretNode.firstChild, 1);
rng.setEnd(caretNode.firstChild, 1);
editor.selection.setRng(rng);
} else {
editor.selection.setContent(charText);
}
}
});
editor.addCommand('Delete', function() {
customDelete();
});
editor.addCommand('ForwardDelete', function() {
customDelete(true);
});
// Older WebKits doesn't properly handle the clipboard so we can't add the rest
if (olderWebKit) {
return;
}
editor.on('dragstart', function(e) {
dragStartRng = selection.getRng();
setMceInternalContent(e);
});
editor.on('drop', function(e) {
if (!isDefaultPrevented(e)) {
var internalContent = getMceInternalContent(e);
if (internalContent) {
e.preventDefault();
// Safari has a weird issue where drag/dropping images sometimes
// produces a green plus icon. When this happens the caretRangeFromPoint
// will return "null" even though the x, y coordinate is correct.
// But if we detach the insert from the drop event we will get a proper range
Delay.setEditorTimeout(editor, function() {
var pointRng = RangeUtils.getCaretRangeFromPoint(e.x, e.y, doc);
if (dragStartRng) {
selection.setRng(dragStartRng);
dragStartRng = null;
}
customDelete();
selection.setRng(pointRng);
insertClipboardContents(internalContent.html);
});
}
}
});
editor.on('cut', function(e) {
if (!isDefaultPrevented(e) && e.clipboardData && !editor.selection.isCollapsed()) {
e.preventDefault();
e.clipboardData.clearData();
e.clipboardData.setData('text/html', editor.selection.getContent());
e.clipboardData.setData('text/plain', editor.selection.getContent({format: 'text'}));
// Needed delay for https://code.google.com/p/chromium/issues/detail?id=363288#c3
// Nested delete/forwardDelete not allowed on execCommand("cut")
// This is ugly but not sure how to work around it otherwise
Delay.setEditorTimeout(editor, function() {
customDelete(true);
});
}
});
}
/**
* Makes sure that the editor body becomes empty when backspace or delete is pressed in empty editors.
*
* For example:
* <p><b>|</b></p>
*
* Or:
* <h1>|</h1>
*
* Or:
* [<h1></h1>]
*/
function emptyEditorWhenDeleting() {
function serializeRng(rng) {
var body = dom.create("body");
var contents = rng.cloneContents();
body.appendChild(contents);
return selection.serializer.serialize(body, {format: 'html'});
}
function allContentsSelected(rng) {
if (!rng.setStart) {
if (rng.item) {
return false;
}
var bodyRng = rng.duplicate();
bodyRng.moveToElementText(editor.getBody());
return RangeUtils.compareRanges(rng, bodyRng);
}
var selection = serializeRng(rng);
var allRng = dom.createRng();
allRng.selectNode(editor.getBody());
var allSelection = serializeRng(allRng);
return selection === allSelection;
}
editor.on('keydown', function(e) {
var keyCode = e.keyCode, isCollapsed, body;
// Empty the editor if it's needed for example backspace at <p><b>|</b></p>
if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) {
isCollapsed = editor.selection.isCollapsed();
body = editor.getBody();
// Selection is collapsed but the editor isn't empty
if (isCollapsed && !dom.isEmpty(body)) {
return;
}
// Selection isn't collapsed but not all the contents is selected
if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
return;
}
// Manually empty the editor
e.preventDefault();
editor.setContent('');
if (body.firstChild && dom.isBlock(body.firstChild)) {
editor.selection.setCursorLocation(body.firstChild, 0);
} else {
editor.selection.setCursorLocation(body, 0);
}
editor.nodeChanged();
}
});
}
/**
* WebKit doesn't select all the nodes in the body when you press Ctrl+A.
* IE selects more than the contents <body>[<p>a</p>]</body> instead of <body><p>[a]</p]</body> see bug #6438
* This selects the whole body so that backspace/delete logic will delete everything
*/
function selectAll() {
editor.shortcuts.add('meta+a', null, 'SelectAll');
}
/**
* WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes.
* The IME on Mac doesn't initialize when it doesn't fire a proper focus event.
*
* This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until
* you enter a character into the editor.
*
* It also happens when the first focus in made to the body.
*
* See: https://bugs.webkit.org/show_bug.cgi?id=83566
*/
function inputMethodFocus() {
if (!editor.settings.content_editable) {
// Case 1 IME doesn't initialize if you focus the document
// Disabled since it was interferring with the cE=false logic
// Also coultn't reproduce the issue on Safari 9
/*dom.bind(editor.getDoc(), 'focusin', function() {
selection.setRng(selection.getRng());
});*/
// Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event
// Needs to be both down/up due to weird rendering bug on Chrome Windows
dom.bind(editor.getDoc(), 'mousedown mouseup', function(e) {
var rng;
if (e.target == editor.getDoc().documentElement) {
rng = selection.getRng();
editor.getBody().focus();
if (e.type == 'mousedown') {
if (CaretContainer.isCaretContainer(rng.startContainer)) {
return;
}
// Edge case for mousedown, drag select and mousedown again within selection on Chrome Windows to render caret
selection.placeCaretAt(e.clientX, e.clientY);
} else {
selection.setRng(rng);
}
}
});
}
}
/**
* Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the
* browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is
* left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js
* addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other
* browsers.
*
* It also fixes a bug on Firefox where it's impossible to delete HR elements.
*/
function removeHrOnBackspace() {
editor.on('keydown', function(e) {
if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
// Check if there is any HR elements this is faster since getRng on IE 7 & 8 is slow
if (!editor.getBody().getElementsByTagName('hr').length) {
return;
}
if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) {
var node = selection.getNode();
var previousSibling = node.previousSibling;
if (node.nodeName == 'HR') {
dom.remove(node);
e.preventDefault();
return;
}
if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") {
dom.remove(previousSibling);
e.preventDefault();
}
}
}
});
}
/**
* Firefox 3.x has an issue where the body element won't get proper focus if you click out
* side it's rectangle.
*/
function focusBody() {
// Fix for a focus bug in FF 3.x where the body element
// wouldn't get proper focus if the user clicked on the HTML element
if (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4
editor.on('mousedown', function(e) {
if (!isDefaultPrevented(e) && e.target.nodeName === "HTML") {
var body = editor.getBody();
// Blur the body it's focused but not correctly focused
body.blur();
// Refocus the body after a little while
Delay.setEditorTimeout(editor, function() {
body.focus();
});
}
});
}
}
/**
* WebKit has a bug where it isn't possible to select image, hr or anchor elements
* by clicking on them so we need to fake that.
*/
function selectControlElements() {
editor.on('click', function(e) {
var target = e.target;
// Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250
// WebKit can't even do simple things like selecting an image
// Needs to be the setBaseAndExtend or it will fail to select floated images
if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== "false") {
e.preventDefault();
selection.getSel().setBaseAndExtent(target, 0, target, 1);
editor.nodeChanged();
}
if (target.nodeName == 'A' && dom.hasClass(target, 'mce-item-anchor')) {
e.preventDefault();
selection.select(target);
}
});
}
/**
* Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements.
*
* Fixes do backspace/delete on this:
* <p>bla[ck</p><p style="color:red">r]ed</p>
*
* Would become:
* <p>bla|ed</p>
*
* Instead of:
* <p style="color:red">bla|ed</p>
*/
function removeStylesWhenDeletingAcrossBlockElements() {
function getAttributeApplyFunction() {
var template = dom.getAttribs(selection.getStart().cloneNode(false));
return function() {
var target = selection.getStart();
if (target !== editor.getBody()) {
dom.setAttrib(target, "style", null);
each(template, function(attr) {
target.setAttributeNode(attr.cloneNode(true));
});
}
};
}
function isSelectionAcrossElements() {
return !selection.isCollapsed() &&
dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock);
}
editor.on('keypress', function(e) {
var applyAttributes;
if (!isDefaultPrevented(e) && (e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) {
applyAttributes = getAttributeApplyFunction();
editor.getDoc().execCommand('delete', false, null);
applyAttributes();
e.preventDefault();
return false;
}
});
dom.bind(editor.getDoc(), 'cut', function(e) {
var applyAttributes;
if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
applyAttributes = getAttributeApplyFunction();
Delay.setEditorTimeout(editor, function() {
applyAttributes();
});
}
});
}
/**
* Screen readers on IE needs to have the role application set on the body.
*/
function ensureBodyHasRoleApplication() {
document.body.setAttribute("role", "application");
}
/**
* Backspacing into a table behaves differently depending upon browser type.
* Therefore, disable Backspace when cursor immediately follows a table.
*/
function disableBackspaceIntoATable() {
editor.on('keydown', function(e) {
if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) {
var previousSibling = selection.getNode().previousSibling;
if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") {
e.preventDefault();
return false;
}
}
}
});
}
/**
* Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this
* logic adds a \n before the BR so that it will get rendered.
*/
function addNewLinesBeforeBrInPre() {
// IE8+ rendering mode does the right thing with BR in PRE
if (getDocumentMode() > 7) {
return;
}
// Enable display: none in area and add a specific class that hides all BR elements in PRE to
// avoid the caret from getting stuck at the BR elements while pressing the right arrow key
setEditorCommandState('RespectVisibilityInDesign', true);
editor.contentStyles.push('.mceHideBrInPre pre br {display: none}');
dom.addClass(editor.getBody(), 'mceHideBrInPre');
// Adds a \n before all BR elements in PRE to get them visual
parser.addNodeFilter('pre', function(nodes) {
var i = nodes.length, brNodes, j, brElm, sibling;
while (i--) {
brNodes = nodes[i].getAll('br');
j = brNodes.length;
while (j--) {
brElm = brNodes[j];
// Add \n before BR in PRE elements on older IE:s so the new lines get rendered
sibling = brElm.prev;
if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') {
sibling.value += '\n';
} else {
brElm.parent.insert(new Node('#text', 3), brElm, true).value = '\n';
}
}
}
});
// Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible
serializer.addNodeFilter('pre', function(nodes) {
var i = nodes.length, brNodes, j, brElm, sibling;
while (i--) {
brNodes = nodes[i].getAll('br');
j = brNodes.length;
while (j--) {
brElm = brNodes[j];
sibling = brElm.prev;
if (sibling && sibling.type == 3) {
sibling.value = sibling.value.replace(/\r?\n$/, '');
}
}
}
});
}
/**
* Moves style width/height to attribute width/height when the user resizes an image on IE.
*/
function removePreSerializedStylesWhenSelectingControls() {
dom.bind(editor.getBody(), 'mouseup', function() {
var value, node = selection.getNode();
// Moved styles to attributes on IMG eements
if (node.nodeName == 'IMG') {
// Convert style width to width attribute
if ((value = dom.getStyle(node, 'width'))) {
dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, ''));
dom.setStyle(node, 'width', '');
}
// Convert style height to height attribute
if ((value = dom.getStyle(node, 'height'))) {
dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, ''));
dom.setStyle(node, 'height', '');
}
}
});
}
/**
* Removes a blockquote when backspace is pressed at the beginning of it.
*
* For example:
* <blockquote><p>|x</p></blockquote>
*
* Becomes:
* <p>|x</p>
*/
function removeBlockQuoteOnBackSpace() {
// Add block quote deletion handler
editor.on('keydown', function(e) {
var rng, container, offset, root, parent;
if (isDefaultPrevented(e) || e.keyCode != VK.BACKSPACE) {
return;
}
rng = selection.getRng();
container = rng.startContainer;
offset = rng.startOffset;
root = dom.getRoot();
parent = container;
if (!rng.collapsed || offset !== 0) {
return;
}
while (parent && parent.parentNode && parent.parentNode.firstChild == parent && parent.parentNode != root) {
parent = parent.parentNode;
}
// Is the cursor at the beginning of a blockquote?
if (parent.tagName === 'BLOCKQUOTE') {
// Remove the blockquote
editor.formatter.toggle('blockquote', null, parent);
// Move the caret to the beginning of container
rng = dom.createRng();
rng.setStart(container, 0);
rng.setEnd(container, 0);
selection.setRng(rng);
}
});
}
/**
* Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc.
*/
function setGeckoEditingOptions() {
function setOpts() {
refreshContentEditable();
setEditorCommandState("StyleWithCSS", false);
setEditorCommandState("enableInlineTableEditing", false);
if (!settings.object_resizing) {
setEditorCommandState("enableObjectResizing", false);
}
}
if (!settings.readonly) {
editor.on('BeforeExecCommand MouseDown', setOpts);
}
}
/**
* Fixes a gecko link bug, when a link is placed at the end of block elements there is
* no way to move the caret behind the link. This fix adds a bogus br element after the link.
*
* For example this:
* <p><b><a href="#">x</a></b></p>
*
* Becomes this:
* <p><b><a href="#">x</a></b><br></p>
*/
function addBrAfterLastLinks() {
function fixLinks() {
each(dom.select('a'), function(node) {
var parentNode = node.parentNode, root = dom.getRoot();
if (parentNode.lastChild === node) {
while (parentNode && !dom.isBlock(parentNode)) {
if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
return;
}
parentNode = parentNode.parentNode;
}
dom.add(parentNode, 'br', {'data-mce-bogus': 1});
}
});
}
editor.on('SetContent ExecCommand', function(e) {
if (e.type == "setcontent" || e.command === 'mceInsertLink') {
fixLinks();
}
});
}
/**
* WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by
* default we want to change that behavior.
*/
function setDefaultBlockType() {
if (settings.forced_root_block) {
editor.on('init', function() {
setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block);
});
}
}
/**
* Deletes the selected image on IE instead of navigating to previous page.
*/
function deleteControlItemOnBackSpace() {
editor.on('keydown', function(e) {
var rng;
if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) {
rng = editor.getDoc().selection.createRange();
if (rng && rng.item) {
e.preventDefault();
editor.undoManager.beforeChange();
dom.remove(rng.item(0));
editor.undoManager.add();
}
}
});
}
/**
* IE10 doesn't properly render block elements with the right height until you add contents to them.
* This fixes that by adding a padding-right to all empty text block elements.
* See: https://connect.microsoft.com/IE/feedback/details/743881
*/
function renderEmptyBlocksFix() {
var emptyBlocksCSS;
// IE10+
if (getDocumentMode() >= 10) {
emptyBlocksCSS = '';
each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) {
emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty';
});
editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}');
}
}
/**
* Old IE versions can't retain contents within noscript elements so this logic will store the contents
* as a attribute and the insert that value as it's raw text when the DOM is serialized.
*/
function keepNoScriptContents() {
if (getDocumentMode() < 9) {
parser.addNodeFilter('noscript', function(nodes) {
var i = nodes.length, node, textNode;
while (i--) {
node = nodes[i];
textNode = node.firstChild;
if (textNode) {
node.attr('data-mce-innertext', textNode.value);
}
}
});
serializer.addNodeFilter('noscript', function(nodes) {
var i = nodes.length, node, textNode, value;
while (i--) {
node = nodes[i];
textNode = nodes[i].firstChild;
if (textNode) {
textNode.value = Entities.decode(textNode.value);
} else {
// Old IE can't retain noscript value so an attribute is used to store it
value = node.attributes.map['data-mce-innertext'];
if (value) {
node.attr('data-mce-innertext', null);
textNode = new Node('#text', 3);
textNode.value = value;
textNode.raw = true;
node.append(textNode);
}
}
}
});
}
}
/**
* IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode.
*/
function fixCaretSelectionOfDocumentElementOnIe() {
var doc = dom.doc, body = doc.body, started, startRng, htmlElm;
// Return range from point or null if it failed
function rngFromPoint(x, y) {
var rng = body.createTextRange();
try {
rng.moveToPoint(x, y);
} catch (ex) {
// IE sometimes throws and exception, so lets just ignore it
rng = null;
}
return rng;
}
// Fires while the selection is changing
function selectionChange(e) {
var pointRng;
// Check if the button is down or not
if (e.button) {
// Create range from mouse position
pointRng = rngFromPoint(e.x, e.y);
if (pointRng) {
// Check if pointRange is before/after selection then change the endPoint
if (pointRng.compareEndPoints('StartToStart', startRng) > 0) {
pointRng.setEndPoint('StartToStart', startRng);
} else {
pointRng.setEndPoint('EndToEnd', startRng);
}
pointRng.select();
}
} else {
endSelection();
}
}
// Removes listeners
function endSelection() {
var rng = doc.selection.createRange();
// If the range is collapsed then use the last start range
if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) {
startRng.select();
}
dom.unbind(doc, 'mouseup', endSelection);
dom.unbind(doc, 'mousemove', selectionChange);
startRng = started = 0;
}
// Make HTML element unselectable since we are going to handle selection by hand
doc.documentElement.unselectable = true;
// Detect when user selects outside BODY
dom.bind(doc, 'mousedown contextmenu', function(e) {
if (e.target.nodeName === 'HTML') {
if (started) {
endSelection();
}
// Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML
htmlElm = doc.documentElement;
if (htmlElm.scrollHeight > htmlElm.clientHeight) {
return;
}
started = 1;
// Setup start position
startRng = rngFromPoint(e.x, e.y);
if (startRng) {
// Listen for selection change events
dom.bind(doc, 'mouseup', endSelection);
dom.bind(doc, 'mousemove', selectionChange);
dom.getRoot().focus();
startRng.select();
}
}
});
}
/**
* Fixes selection issues where the caret can be placed between two inline elements like <b>a</b>|<b>b</b>
* this fix will lean the caret right into the closest inline element.
*/
function normalizeSelection() {
// Normalize selection for example <b>a</b><i>|a</i> becomes <b>a|</b><i>a</i> except for Ctrl+A since it selects everything
editor.on('keyup focusin mouseup', function(e) {
if (e.keyCode != 65 || !VK.metaKeyPressed(e)) {
selection.normalize();
}
}, true);
}
/**
* Forces Gecko to render a broken image icon if it fails to load an image.
*/
function showBrokenImageIcon() {
editor.contentStyles.push(
'img:-moz-broken {' +
'-moz-force-broken-image-icon:1;' +
'min-width:24px;' +
'min-height:24px' +
'}'
);
}
/**
* iOS has a bug where it's impossible to type if the document has a touchstart event
* bound and the user touches the document while having the on screen keyboard visible.
*
* The touch event moves the focus to the parent document while having the caret inside the iframe
* this fix moves the focus back into the iframe document.
*/
function restoreFocusOnKeyDown() {
if (!editor.inline) {
editor.on('keydown', function() {
if (document.activeElement == document.body) {
editor.getWin().focus();
}
});
}
}
/**
* IE 11 has an annoying issue where you can't move focus into the editor
* by clicking on the white area HTML element. We used to be able to to fix this with
* the fixCaretSelectionOfDocumentElementOnIe fix. But since M$ removed the selection
* object it's not possible anymore. So we need to hack in a ungly CSS to force the
* body to be at least 150px. If the user clicks the HTML element out side this 150px region
* we simply move the focus into the first paragraph. Not ideal since you loose the
* positioning of the caret but goot enough for most cases.
*/
function bodyHeight() {
if (!editor.inline) {
editor.contentStyles.push('body {min-height: 150px}');
editor.on('click', function(e) {
var rng;
if (e.target.nodeName == 'HTML') {
// Edge seems to only need focus if we set the range
// the caret will become invisible and moved out of the iframe!!
if (Env.ie > 11) {
editor.getBody().focus();
return;
}
// Need to store away non collapsed ranges since the focus call will mess that up see #7382
rng = editor.selection.getRng();
editor.getBody().focus();
editor.selection.setRng(rng);
editor.selection.normalize();
editor.nodeChanged();
}
});
}
}
/**
* Firefox on Mac OS will move the browser back to the previous page if you press CMD+Left arrow.
* You might then loose all your work so we need to block that behavior and replace it with our own.
*/
function blockCmdArrowNavigation() {
if (Env.mac) {
editor.on('keydown', function(e) {
if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode == 37 || e.keyCode == 39)) {
e.preventDefault();
editor.selection.getSel().modify('move', e.keyCode == 37 ? 'backward' : 'forward', 'lineboundary');
}
});
}
}
/**
* Disables the autolinking in IE 9+ this is then re-enabled by the autolink plugin.
*/
function disableAutoUrlDetect() {
setEditorCommandState("AutoUrlDetect", false);
}
/**
* iOS 7.1 introduced two new bugs:
* 1) It's possible to open links within a contentEditable area by clicking on them.
* 2) If you hold down the finger it will display the link/image touch callout menu.
*/
function tapLinksAndImages() {
editor.on('click', function(e) {
var elm = e.target;
do {
if (elm.tagName === 'A') {
e.preventDefault();
return;
}
} while ((elm = elm.parentNode));
});
editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
}
/**
* iOS Safari and possible other browsers have a bug where it won't fire
* a click event when a contentEditable is focused. This function fakes click events
* by using touchstart/touchend and measuring the time and distance travelled.
*/
/*
function touchClickEvent() {
editor.on('touchstart', function(e) {
var elm, time, startTouch, changedTouches;
elm = e.target;
time = new Date().getTime();
changedTouches = e.changedTouches;
if (!changedTouches || changedTouches.length > 1) {
return;
}
startTouch = changedTouches[0];
editor.once('touchend', function(e) {
var endTouch = e.changedTouches[0], args;
if (new Date().getTime() - time > 500) {
return;
}
if (Math.abs(startTouch.clientX - endTouch.clientX) > 5) {
return;
}
if (Math.abs(startTouch.clientY - endTouch.clientY) > 5) {
return;
}
args = {
target: elm
};
each('pageX pageY clientX clientY screenX screenY'.split(' '), function(key) {
args[key] = endTouch[key];
});
args = editor.fire('click', args);
if (!args.isDefaultPrevented()) {
// iOS WebKit can't place the caret properly once
// you bind touch events so we need to do this manually
// TODO: Expand to the closest word? Touble tap still works.
editor.selection.placeCaretAt(endTouch.clientX, endTouch.clientY);
editor.nodeChanged();
}
});
});
}
*/
/**
* WebKit has a bug where it will allow forms to be submitted if they are inside a contentEditable element.
* For example this: <form><button></form>
*/
function blockFormSubmitInsideEditor() {
editor.on('init', function() {
editor.dom.bind(editor.getBody(), 'submit', function(e) {
e.preventDefault();
});
});
}
/**
* Sometimes WebKit/Blink generates BR elements with the Apple-interchange-newline class.
*
* Scenario:
* 1) Create a table 2x2.
* 2) Select and copy cells A2-B2.
* 3) Paste and it will add BR element to table cell.
*/
function removeAppleInterchangeBrs() {
parser.addNodeFilter('br', function(nodes) {
var i = nodes.length;
while (i--) {
if (nodes[i].attr('class') == 'Apple-interchange-newline') {
nodes[i].remove();
}
}
});
}
/**
* IE cannot set custom contentType's on drag events, and also does not properly drag/drop between
* editors. This uses a special data:text/mce-internal URL to pass data when drag/drop between editors.
*/
function ieInternalDragAndDrop() {
editor.on('dragstart', function(e) {
setMceInternalContent(e);
});
editor.on('drop', function(e) {
if (!isDefaultPrevented(e)) {
var internalContent = getMceInternalContent(e);
if (internalContent && internalContent.id != editor.id) {
e.preventDefault();
var rng = RangeUtils.getCaretRangeFromPoint(e.x, e.y, editor.getDoc());
selection.setRng(rng);
insertClipboardContents(internalContent.html);
}
}
});
}
function refreshContentEditable() {
var body, parent;
// Check if the editor was hidden and the re-initialize contentEditable mode by removing and adding the body again
if (isHidden()) {
body = editor.getBody();
parent = body.parentNode;
parent.removeChild(body);
parent.appendChild(body);
body.focus();
}
}
function isHidden() {
var sel;
if (!isGecko) {
return 0;
}
// Weird, wheres that cursor selection?
sel = editor.selection.getSel();
return (!sel || !sel.rangeCount || sel.rangeCount === 0);
}
/**
* Properly empties the editor if all contents is selected and deleted this to
* prevent empty paragraphs from being produced at beginning/end of contents.
*/
function emptyEditorOnDeleteEverything() {
function isEverythingSelected(editor) {
var caretWalker = new CaretWalker(editor.getBody());
var rng = editor.selection.getRng();
var startCaretPos = CaretPosition.fromRangeStart(rng);
var endCaretPos = CaretPosition.fromRangeEnd(rng);
return !editor.selection.isCollapsed() && !caretWalker.prev(startCaretPos) && !caretWalker.next(endCaretPos);
}
// Type over case delete and insert this won't cover typeover with a IME but at least it covers the common case
editor.on('keypress', function (e) {
if (!isDefaultPrevented(e) && !selection.isCollapsed() && e.charCode > 31 && !VK.metaKeyPressed(e)) {
if (isEverythingSelected(editor)) {
e.preventDefault();
editor.setContent(String.fromCharCode(e.charCode));
editor.selection.select(editor.getBody(), true);
editor.selection.collapse(false);
editor.nodeChanged();
}
}
});
editor.on('keydown', function (e) {
var keyCode = e.keyCode;
if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) {
if (isEverythingSelected(editor)) {
e.preventDefault();
editor.setContent('');
editor.nodeChanged();
}
}
});
}
// All browsers
removeBlockQuoteOnBackSpace();
emptyEditorWhenDeleting();
// Windows phone will return a range like [body, 0] on mousedown so
// it will always normalize to the wrong location
if (!Env.windowsPhone) {
normalizeSelection();
}
// WebKit
if (isWebKit) {
emptyEditorOnDeleteEverything();
cleanupStylesWhenDeleting();
inputMethodFocus();
selectControlElements();
setDefaultBlockType();
blockFormSubmitInsideEditor();
disableBackspaceIntoATable();
removeAppleInterchangeBrs();
//touchClickEvent();
// iOS
if (Env.iOS) {
restoreFocusOnKeyDown();
bodyHeight();
tapLinksAndImages();
} else {
selectAll();
}
}
// IE
if (isIE && Env.ie < 11) {
removeHrOnBackspace();
ensureBodyHasRoleApplication();
addNewLinesBeforeBrInPre();
removePreSerializedStylesWhenSelectingControls();
deleteControlItemOnBackSpace();
renderEmptyBlocksFix();
keepNoScriptContents();
fixCaretSelectionOfDocumentElementOnIe();
}
if (Env.ie >= 11) {
bodyHeight();
disableBackspaceIntoATable();
}
if (Env.ie) {
selectAll();
disableAutoUrlDetect();
ieInternalDragAndDrop();
}
// Gecko
if (isGecko) {
emptyEditorOnDeleteEverything();
removeHrOnBackspace();
focusBody();
removeStylesWhenDeletingAcrossBlockElements();
setGeckoEditingOptions();
addBrAfterLastLinks();
showBrokenImageIcon();
blockCmdArrowNavigation();
disableBackspaceIntoATable();
}
return {
refreshContentEditable: refreshContentEditable,
isHidden: isHidden
};
};
});