Editor.js
63.7 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
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
/**
* Editor.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
*/
/*jshint scripturl:true */
/**
* Include the base event class documentation.
*
* @include ../../../tools/docs/tinymce.Event.js
*/
/**
* This class contains the core logic for a TinyMCE editor.
*
* @class tinymce.Editor
* @mixes tinymce.util.Observable
* @example
* // Add a class to all paragraphs in the editor.
* tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass');
*
* // Gets the current editors selection as text
* tinymce.activeEditor.selection.getContent({format: 'text'});
*
* // Creates a new editor instance
* var ed = new tinymce.Editor('textareaid', {
* some_setting: 1
* }, tinymce.EditorManager);
*
* // Select each item the user clicks on
* ed.on('click', function(e) {
* ed.selection.select(e.target);
* });
*
* ed.render();
*/
define("tinymce/Editor", [
"tinymce/dom/DOMUtils",
"tinymce/dom/DomQuery",
"tinymce/AddOnManager",
"tinymce/NodeChange",
"tinymce/html/Node",
"tinymce/dom/Serializer",
"tinymce/html/Serializer",
"tinymce/dom/Selection",
"tinymce/Formatter",
"tinymce/UndoManager",
"tinymce/EnterKey",
"tinymce/ForceBlocks",
"tinymce/EditorCommands",
"tinymce/util/URI",
"tinymce/dom/ScriptLoader",
"tinymce/dom/EventUtils",
"tinymce/WindowManager",
"tinymce/NotificationManager",
"tinymce/html/Schema",
"tinymce/html/DomParser",
"tinymce/util/Quirks",
"tinymce/Env",
"tinymce/util/Tools",
"tinymce/util/Delay",
"tinymce/EditorObservable",
"tinymce/Mode",
"tinymce/Shortcuts",
"tinymce/EditorUpload",
"tinymce/SelectionOverrides",
"tinymce/util/Uuid"
], function(
DOMUtils, DomQuery, AddOnManager, NodeChange, Node, DomSerializer, Serializer,
Selection, Formatter, UndoManager, EnterKey, ForceBlocks, EditorCommands,
URI, ScriptLoader, EventUtils, WindowManager, NotificationManager,
Schema, DomParser, Quirks, Env, Tools, Delay, EditorObservable, Mode, Shortcuts, EditorUpload,
SelectionOverrides, Uuid
) {
// Shorten these names
var DOM = DOMUtils.DOM, ThemeManager = AddOnManager.ThemeManager, PluginManager = AddOnManager.PluginManager;
var extend = Tools.extend, each = Tools.each, explode = Tools.explode;
var inArray = Tools.inArray, trim = Tools.trim, resolve = Tools.resolve;
var Event = EventUtils.Event;
var isGecko = Env.gecko, ie = Env.ie;
/**
* Include documentation for all the events.
*
* @include ../../../tools/docs/tinymce.Editor.js
*/
/**
* Constructs a editor instance by id.
*
* @constructor
* @method Editor
* @param {String} id Unique id for the editor.
* @param {Object} settings Settings for the editor.
* @param {tinymce.EditorManager} editorManager EditorManager instance.
*/
function Editor(id, settings, editorManager) {
var self = this, documentBaseUrl, baseUri, defaultSettings;
documentBaseUrl = self.documentBaseUrl = editorManager.documentBaseURL;
baseUri = editorManager.baseURI;
defaultSettings = editorManager.defaultSettings;
/**
* Name/value collection with editor settings.
*
* @property settings
* @type Object
* @example
* // Get the value of the theme setting
* tinymce.activeEditor.windowManager.alert("You are using the " + tinymce.activeEditor.settings.theme + " theme");
*/
settings = extend({
id: id,
theme: 'modern',
delta_width: 0,
delta_height: 0,
popup_css: '',
plugins: '',
document_base_url: documentBaseUrl,
add_form_submit_trigger: true,
submit_patch: true,
add_unload_trigger: true,
convert_urls: true,
relative_urls: true,
remove_script_host: true,
object_resizing: true,
doctype: '<!DOCTYPE html>',
visual: true,
font_size_style_values: 'xx-small,x-small,small,medium,large,x-large,xx-large',
// See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size
font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
forced_root_block: 'p',
hidden_input: true,
padd_empty_editor: true,
render_ui: true,
indentation: '30px',
inline_styles: true,
convert_fonts_to_spans: true,
indent: 'simple',
indent_before: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' +
'tfoot,tbody,tr,section,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
indent_after: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,th,ul,ol,li,dl,dt,dd,area,table,thead,' +
'tfoot,tbody,tr,section,article,hgroup,aside,figure,figcaption,option,optgroup,datalist',
validate: true,
entity_encoding: 'named',
url_converter: self.convertURL,
url_converter_scope: self,
ie7_compat: true
}, defaultSettings, settings);
// Merge external_plugins
if (defaultSettings && defaultSettings.external_plugins && settings.external_plugins) {
settings.external_plugins = extend({}, defaultSettings.external_plugins, settings.external_plugins);
}
self.settings = settings;
AddOnManager.language = settings.language || 'en';
AddOnManager.languageLoad = settings.language_load;
AddOnManager.baseURL = editorManager.baseURL;
/**
* Editor instance id, normally the same as the div/textarea that was replaced.
*
* @property id
* @type String
*/
self.id = settings.id = id;
/**
* State to force the editor to return false on a isDirty call.
*
* @property isNotDirty
* @type Boolean
* @deprecated Use editor.setDirty instead.
*/
self.setDirty(false);
/**
* Name/Value object containing plugin instances.
*
* @property plugins
* @type Object
* @example
* // Execute a method inside a plugin directly
* tinymce.activeEditor.plugins.someplugin.someMethod();
*/
self.plugins = {};
/**
* URI object to document configured for the TinyMCE instance.
*
* @property documentBaseURI
* @type tinymce.util.URI
* @example
* // Get relative URL from the location of document_base_url
* tinymce.activeEditor.documentBaseURI.toRelative('/somedir/somefile.htm');
*
* // Get absolute URL from the location of document_base_url
* tinymce.activeEditor.documentBaseURI.toAbsolute('somefile.htm');
*/
self.documentBaseURI = new URI(settings.document_base_url || documentBaseUrl, {
base_uri: baseUri
});
/**
* URI object to current document that holds the TinyMCE editor instance.
*
* @property baseURI
* @type tinymce.util.URI
* @example
* // Get relative URL from the location of the API
* tinymce.activeEditor.baseURI.toRelative('/somedir/somefile.htm');
*
* // Get absolute URL from the location of the API
* tinymce.activeEditor.baseURI.toAbsolute('somefile.htm');
*/
self.baseURI = baseUri;
/**
* Array with CSS files to load into the iframe.
*
* @property contentCSS
* @type Array
*/
self.contentCSS = [];
/**
* Array of CSS styles to add to head of document when the editor loads.
*
* @property contentStyles
* @type Array
*/
self.contentStyles = [];
// Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic
self.shortcuts = new Shortcuts(self);
self.loadedCSS = {};
self.editorCommands = new EditorCommands(self);
if (settings.target) {
self.targetElm = settings.target;
}
self.suffix = editorManager.suffix;
self.editorManager = editorManager;
self.inline = settings.inline;
self.settings.content_editable = self.inline;
if (settings.cache_suffix) {
Env.cacheSuffix = settings.cache_suffix.replace(/^[\?\&]+/, '');
}
if (settings.override_viewport === false) {
Env.overrideViewPort = false;
}
// Call setup
editorManager.fire('SetupEditor', self);
self.execCallback('setup', self);
/**
* Dom query instance with default scope to the editor document and default element is the body of the editor.
*
* @property $
* @type tinymce.dom.DomQuery
* @example
* tinymce.activeEditor.$('p').css('color', 'red');
* tinymce.activeEditor.$().append('<p>new</p>');
*/
self.$ = DomQuery.overrideDefaults(function() {
return {
context: self.inline ? self.getBody() : self.getDoc(),
element: self.getBody()
};
});
}
Editor.prototype = {
/**
* Renders the editor/adds it to the page.
*
* @method render
*/
render: function() {
var self = this, settings = self.settings, id = self.id, suffix = self.suffix;
function readyHandler() {
DOM.unbind(window, 'ready', readyHandler);
self.render();
}
// Page is not loaded yet, wait for it
if (!Event.domLoaded) {
DOM.bind(window, 'ready', readyHandler);
return;
}
// Element not found, then skip initialization
if (!self.getElement()) {
return;
}
// No editable support old iOS versions etc
if (!Env.contentEditable) {
return;
}
// Hide target element early to prevent content flashing
if (!settings.inline) {
self.orgVisibility = self.getElement().style.visibility;
self.getElement().style.visibility = 'hidden';
} else {
self.inline = true;
}
var form = self.getElement().form || DOM.getParent(id, 'form');
if (form) {
self.formElement = form;
// Add hidden input for non input elements inside form elements
if (settings.hidden_input && !/TEXTAREA|INPUT/i.test(self.getElement().nodeName)) {
DOM.insertAfter(DOM.create('input', {type: 'hidden', name: id}), id);
self.hasHiddenInput = true;
}
// Pass submit/reset from form to editor instance
self.formEventDelegate = function(e) {
self.fire(e.type, e);
};
DOM.bind(form, 'submit reset', self.formEventDelegate);
// Reset contents in editor when the form is reset
self.on('reset', function() {
self.setContent(self.startContent, {format: 'raw'});
});
// Check page uses id="submit" or name="submit" for it's submit button
if (settings.submit_patch && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
form._mceOldSubmit = form.submit;
form.submit = function() {
self.editorManager.triggerSave();
self.setDirty(false);
return form._mceOldSubmit(form);
};
}
}
/**
* Window manager reference, use this to open new windows and dialogs.
*
* @property windowManager
* @type tinymce.WindowManager
* @example
* // Shows an alert message
* tinymce.activeEditor.windowManager.alert('Hello world!');
*
* // Opens a new dialog with the file.htm file and the size 320x240
* // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog.
* tinymce.activeEditor.windowManager.open({
* url: 'file.htm',
* width: 320,
* height: 240
* }, {
* custom_param: 1
* });
*/
self.windowManager = new WindowManager(self);
/**
* Notification manager reference, use this to open new windows and dialogs.
*
* @property notificationManager
* @type tinymce.NotificationManager
* @example
* // Shows a notification info message.
* tinymce.activeEditor.notificationManager.open({text: 'Hello world!', type: 'info'});
*/
self.notificationManager = new NotificationManager(self);
if (settings.encoding == 'xml') {
self.on('GetContent', function(e) {
if (e.save) {
e.content = DOM.encode(e.content);
}
});
}
if (settings.add_form_submit_trigger) {
self.on('submit', function() {
if (self.initialized) {
self.save();
}
});
}
if (settings.add_unload_trigger) {
self._beforeUnload = function() {
if (self.initialized && !self.destroyed && !self.isHidden()) {
self.save({format: 'raw', no_events: true, set_dirty: false});
}
};
self.editorManager.on('BeforeUnload', self._beforeUnload);
}
// Load scripts
function loadScripts() {
var scriptLoader = ScriptLoader.ScriptLoader;
if (settings.language && settings.language != 'en' && !settings.language_url) {
settings.language_url = self.editorManager.baseURL + '/langs/' + settings.language + '.js';
}
if (settings.language_url) {
scriptLoader.add(settings.language_url);
}
if (settings.theme && typeof settings.theme != "function" &&
settings.theme.charAt(0) != '-' && !ThemeManager.urls[settings.theme]) {
var themeUrl = settings.theme_url;
if (themeUrl) {
themeUrl = self.documentBaseURI.toAbsolute(themeUrl);
} else {
themeUrl = 'themes/' + settings.theme + '/theme' + suffix + '.js';
}
ThemeManager.load(settings.theme, themeUrl);
}
if (Tools.isArray(settings.plugins)) {
settings.plugins = settings.plugins.join(' ');
}
each(settings.external_plugins, function(url, name) {
PluginManager.load(name, url);
settings.plugins += ' ' + name;
});
each(settings.plugins.split(/[ ,]/), function(plugin) {
plugin = trim(plugin);
if (plugin && !PluginManager.urls[plugin]) {
if (plugin.charAt(0) == '-') {
plugin = plugin.substr(1, plugin.length);
var dependencies = PluginManager.dependencies(plugin);
each(dependencies, function(dep) {
var defaultSettings = {
prefix: 'plugins/',
resource: dep,
suffix: '/plugin' + suffix + '.js'
};
dep = PluginManager.createUrl(defaultSettings, dep);
PluginManager.load(dep.resource, dep);
});
} else {
PluginManager.load(plugin, {
prefix: 'plugins/',
resource: plugin,
suffix: '/plugin' + suffix + '.js'
});
}
}
});
scriptLoader.loadQueue(function() {
if (!self.removed) {
self.init();
}
});
}
self.editorManager.add(self);
loadScripts();
},
/**
* Initializes the editor this will be called automatically when
* all plugins/themes and language packs are loaded by the rendered method.
* This method will setup the iframe and create the theme and plugin instances.
*
* @method init
*/
init: function() {
var self = this, settings = self.settings, elm = self.getElement();
var w, h, minHeight, n, o, Theme, url, bodyId, bodyClass, re, i, initializedPlugins = [];
self.rtl = settings.rtl_ui || self.editorManager.i18n.rtl;
self.editorManager.i18n.setCode(settings.language);
settings.aria_label = settings.aria_label || DOM.getAttrib(elm, 'aria-label', self.getLang('aria.rich_text_area'));
self.fire('ScriptsLoaded');
/**
* Reference to the theme instance that was used to generate the UI.
*
* @property theme
* @type tinymce.Theme
* @example
* // Executes a method on the theme directly
* tinymce.activeEditor.theme.someMethod();
*/
if (settings.theme) {
if (typeof settings.theme != "function") {
settings.theme = settings.theme.replace(/-/, '');
Theme = ThemeManager.get(settings.theme);
self.theme = new Theme(self, ThemeManager.urls[settings.theme]);
if (self.theme.init) {
self.theme.init(self, ThemeManager.urls[settings.theme] || self.documentBaseUrl.replace(/\/$/, ''), self.$);
}
} else {
self.theme = settings.theme;
}
}
function initPlugin(plugin) {
var Plugin = PluginManager.get(plugin), pluginUrl, pluginInstance;
pluginUrl = PluginManager.urls[plugin] || self.documentBaseUrl.replace(/\/$/, '');
plugin = trim(plugin);
if (Plugin && inArray(initializedPlugins, plugin) === -1) {
each(PluginManager.dependencies(plugin), function(dep) {
initPlugin(dep);
});
if (self.plugins[plugin]) {
return;
}
pluginInstance = new Plugin(self, pluginUrl, self.$);
self.plugins[plugin] = pluginInstance;
if (pluginInstance.init) {
pluginInstance.init(self, pluginUrl);
initializedPlugins.push(plugin);
}
}
}
// Create all plugins
each(settings.plugins.replace(/\-/g, '').split(/[ ,]/), initPlugin);
// Measure box
if (settings.render_ui && self.theme) {
self.orgDisplay = elm.style.display;
if (typeof settings.theme != "function") {
w = settings.width || elm.style.width || elm.offsetWidth;
h = settings.height || elm.style.height || elm.offsetHeight;
minHeight = settings.min_height || 100;
re = /^[0-9\.]+(|px)$/i;
if (re.test('' + w)) {
w = Math.max(parseInt(w, 10), 100);
}
if (re.test('' + h)) {
h = Math.max(parseInt(h, 10), minHeight);
}
// Render UI
o = self.theme.renderUI({
targetNode: elm,
width: w,
height: h,
deltaWidth: settings.delta_width,
deltaHeight: settings.delta_height
});
// Resize editor
if (!settings.content_editable) {
h = (o.iframeHeight || h) + (typeof h == 'number' ? (o.deltaHeight || 0) : '');
if (h < minHeight) {
h = minHeight;
}
}
} else {
o = settings.theme(self, elm);
// Convert element type to id:s
if (o.editorContainer.nodeType) {
o.editorContainer = o.editorContainer.id = o.editorContainer.id || self.id + "_parent";
}
// Convert element type to id:s
if (o.iframeContainer.nodeType) {
o.iframeContainer = o.iframeContainer.id = o.iframeContainer.id || self.id + "_iframecontainer";
}
// Use specified iframe height or the targets offsetHeight
h = o.iframeHeight || elm.offsetHeight;
}
self.editorContainer = o.editorContainer;
}
// Load specified content CSS last
if (settings.content_css) {
each(explode(settings.content_css), function(u) {
self.contentCSS.push(self.documentBaseURI.toAbsolute(u));
});
}
// Load specified content CSS last
if (settings.content_style) {
self.contentStyles.push(settings.content_style);
}
// Content editable mode ends here
if (settings.content_editable) {
elm = n = o = null; // Fix IE leak
return self.initContentBody();
}
self.iframeHTML = settings.doctype + '<html><head>';
// We only need to override paths if we have to
// IE has a bug where it remove site absolute urls to relative ones if this is specified
if (settings.document_base_url != self.documentBaseUrl) {
self.iframeHTML += '<base href="' + self.documentBaseURI.getURI() + '" />';
}
// IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode.
if (!Env.caretAfter && settings.ie7_compat) {
self.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=7" />';
}
self.iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
// Load the CSS by injecting them into the HTML this will reduce "flicker"
// However we can't do that on Chrome since # will scroll to the editor for some odd reason see #2427
if (!/#$/.test(document.location.href)) {
for (i = 0; i < self.contentCSS.length; i++) {
var cssUrl = self.contentCSS[i];
self.iframeHTML += (
'<link type="text/css" ' +
'rel="stylesheet" ' +
'href="' + Tools._addCacheSuffix(cssUrl) + '" />'
);
self.loadedCSS[cssUrl] = true;
}
}
bodyId = settings.body_id || 'tinymce';
if (bodyId.indexOf('=') != -1) {
bodyId = self.getParam('body_id', '', 'hash');
bodyId = bodyId[self.id] || bodyId;
}
bodyClass = settings.body_class || '';
if (bodyClass.indexOf('=') != -1) {
bodyClass = self.getParam('body_class', '', 'hash');
bodyClass = bodyClass[self.id] || '';
}
if (settings.content_security_policy) {
self.iframeHTML += '<meta http-equiv="Content-Security-Policy" content="' + settings.content_security_policy + '" />';
}
self.iframeHTML += '</head><body id="' + bodyId +
'" class="mce-content-body ' + bodyClass +
'" data-id="' + self.id + '"><br></body></html>';
/*eslint no-script-url:0 */
var domainRelaxUrl = 'javascript:(function(){' +
'document.open();document.domain="' + document.domain + '";' +
'var ed = window.parent.tinymce.get("' + self.id + '");document.write(ed.iframeHTML);' +
'document.close();ed.initContentBody(true);})()';
// Domain relaxing is required since the user has messed around with document.domain
if (document.domain != location.hostname) {
// Edge seems to be able to handle domain relaxing
if (Env.ie && Env.ie < 12) {
url = domainRelaxUrl;
}
}
// Create iframe
// TODO: ACC add the appropriate description on this.
var ifr = DOM.create('iframe', {
id: self.id + "_ifr",
//src: url || 'javascript:""', // Workaround for HTTPS warning in IE6/7
frameBorder: '0',
allowTransparency: "true",
title: self.editorManager.translate(
"Rich Text Area. Press ALT-F9 for menu. " +
"Press ALT-F10 for toolbar. Press ALT-0 for help"
),
style: {
width: '100%',
height: h,
display: 'block' // Important for Gecko to render the iframe correctly
}
});
ifr.onload = function() {
ifr.onload = null;
self.fire("load");
};
DOM.setAttrib(ifr, "src", url || 'javascript:""');
self.contentAreaContainer = o.iframeContainer;
self.iframeElement = ifr;
n = DOM.add(o.iframeContainer, ifr);
// Try accessing the document this will fail on IE when document.domain is set to the same as location.hostname
// Then we have to force domain relaxing using the domainRelaxUrl approach very ugly!!
if (ie) {
try {
self.getDoc();
} catch (e) {
n.src = url = domainRelaxUrl;
}
}
if (o.editorContainer) {
DOM.get(o.editorContainer).style.display = self.orgDisplay;
self.hidden = DOM.isHidden(o.editorContainer);
}
self.getElement().style.display = 'none';
DOM.setAttrib(self.id, 'aria-hidden', true);
if (!url) {
self.initContentBody();
}
elm = n = o = null; // Cleanup
},
/**
* This method get called by the init method once the iframe is loaded.
* It will fill the iframe with contents, sets up DOM and selection objects for the iframe.
*
* @method initContentBody
* @private
*/
initContentBody: function(skipWrite) {
var self = this, settings = self.settings, targetElm = self.getElement(), doc = self.getDoc(), body, contentCssText;
// Restore visibility on target element
if (!settings.inline) {
self.getElement().style.visibility = self.orgVisibility;
}
// Setup iframe body
if (!skipWrite && !settings.content_editable) {
doc.open();
doc.write(self.iframeHTML);
doc.close();
}
if (settings.content_editable) {
self.on('remove', function() {
var bodyEl = this.getBody();
DOM.removeClass(bodyEl, 'mce-content-body');
DOM.removeClass(bodyEl, 'mce-edit-focus');
DOM.setAttrib(bodyEl, 'contentEditable', null);
});
DOM.addClass(targetElm, 'mce-content-body');
self.contentDocument = doc = settings.content_document || document;
self.contentWindow = settings.content_window || window;
self.bodyElement = targetElm;
// Prevent leak in IE
settings.content_document = settings.content_window = null;
// TODO: Fix this
settings.root_name = targetElm.nodeName.toLowerCase();
}
// It will not steal focus while setting contentEditable
body = self.getBody();
body.disabled = true;
self.readonly = settings.readonly;
if (!self.readonly) {
if (self.inline && DOM.getStyle(body, 'position', true) == 'static') {
body.style.position = 'relative';
}
body.contentEditable = self.getParam('content_editable_state', true);
}
body.disabled = false;
self.editorUpload = new EditorUpload(self);
/**
* Schema instance, enables you to validate elements and its children.
*
* @property schema
* @type tinymce.html.Schema
*/
self.schema = new Schema(settings);
/**
* DOM instance for the editor.
*
* @property dom
* @type tinymce.dom.DOMUtils
* @example
* // Adds a class to all paragraphs within the editor
* tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass');
*/
self.dom = new DOMUtils(doc, {
keep_values: true,
url_converter: self.convertURL,
url_converter_scope: self,
hex_colors: settings.force_hex_style_colors,
class_filter: settings.class_filter,
update_styles: true,
root_element: self.inline ? self.getBody() : null,
collect: settings.content_editable,
schema: self.schema,
onSetAttrib: function(e) {
self.fire('SetAttrib', e);
}
});
/**
* HTML parser will be used when contents is inserted into the editor.
*
* @property parser
* @type tinymce.html.DomParser
*/
self.parser = new DomParser(settings, self.schema);
// Convert src and href into data-mce-src, data-mce-href and data-mce-style
self.parser.addAttributeFilter('src,href,style,tabindex', function(nodes, name) {
var i = nodes.length, node, dom = self.dom, value, internalName;
while (i--) {
node = nodes[i];
value = node.attr(name);
internalName = 'data-mce-' + name;
// Add internal attribute if we need to we don't on a refresh of the document
if (!node.attributes.map[internalName]) {
// Don't duplicate these since they won't get modified by any browser
if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) {
continue;
}
if (name === "style") {
value = dom.serializeStyle(dom.parseStyle(value), node.name);
if (!value.length) {
value = null;
}
node.attr(internalName, value);
node.attr(name, value);
} else if (name === "tabindex") {
node.attr(internalName, value);
node.attr(name, null);
} else {
node.attr(internalName, self.convertURL(value, name, node.name));
}
}
}
});
// Keep scripts from executing
self.parser.addNodeFilter('script', function(nodes) {
var i = nodes.length, node, type;
while (i--) {
node = nodes[i];
type = node.attr('type') || 'no/type';
if (type.indexOf('mce-') !== 0) {
node.attr('type', 'mce-' + type);
}
}
});
self.parser.addNodeFilter('#cdata', function(nodes) {
var i = nodes.length, node;
while (i--) {
node = nodes[i];
node.type = 8;
node.name = '#comment';
node.value = '[CDATA[' + node.value + ']]';
}
});
self.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes) {
var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements();
while (i--) {
node = nodes[i];
if (node.isEmpty(nonEmptyElements)) {
node.append(new Node('br', 1)).shortEnded = true;
}
}
});
/**
* DOM serializer for the editor. Will be used when contents is extracted from the editor.
*
* @property serializer
* @type tinymce.dom.Serializer
* @example
* // Serializes the first paragraph in the editor into a string
* tinymce.activeEditor.serializer.serialize(tinymce.activeEditor.dom.select('p')[0]);
*/
self.serializer = new DomSerializer(settings, self);
/**
* Selection instance for the editor.
*
* @property selection
* @type tinymce.dom.Selection
* @example
* // Sets some contents to the current selection in the editor
* tinymce.activeEditor.selection.setContent('Some contents');
*
* // Gets the current selection
* alert(tinymce.activeEditor.selection.getContent());
*
* // Selects the first paragraph found
* tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]);
*/
self.selection = new Selection(self.dom, self.getWin(), self.serializer, self);
/**
* Formatter instance.
*
* @property formatter
* @type tinymce.Formatter
*/
self.formatter = new Formatter(self);
/**
* Undo manager instance, responsible for handling undo levels.
*
* @property undoManager
* @type tinymce.UndoManager
* @example
* // Undoes the last modification to the editor
* tinymce.activeEditor.undoManager.undo();
*/
self.undoManager = new UndoManager(self);
self.forceBlocks = new ForceBlocks(self);
self.enterKey = new EnterKey(self);
self._nodeChangeDispatcher = new NodeChange(self);
self._selectionOverrides = new SelectionOverrides(self);
self.fire('PreInit');
if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
doc.body.spellcheck = false; // Gecko
DOM.setAttrib(body, "spellcheck", "false");
}
self.quirks = new Quirks(self);
self.fire('PostRender');
if (settings.directionality) {
body.dir = settings.directionality;
}
if (settings.nowrap) {
body.style.whiteSpace = "nowrap";
}
if (settings.protect) {
self.on('BeforeSetContent', function(e) {
each(settings.protect, function(pattern) {
e.content = e.content.replace(pattern, function(str) {
return '<!--mce:protected ' + escape(str) + '-->';
});
});
});
}
self.on('SetContent', function() {
self.addVisual(self.getBody());
});
// Remove empty contents
if (settings.padd_empty_editor) {
self.on('PostProcess', function(e) {
e.content = e.content.replace(/^(<p[^>]*>( | |\s|\u00a0|)<\/p>[\r\n]*|<br \/>[\r\n]*)$/, '');
});
}
self.load({initial: true, format: 'html'});
self.startContent = self.getContent({format: 'raw'});
/**
* Is set to true after the editor instance has been initialized
*
* @property initialized
* @type Boolean
* @example
* function isEditorInitialized(editor) {
* return editor && editor.initialized;
* }
*/
self.initialized = true;
self.bindPendingEventDelegates();
self.fire('init');
self.focus(true);
self.nodeChanged({initial: true});
self.execCallback('init_instance_callback', self);
self.on('compositionstart compositionend', function(e) {
self.composing = e.type === 'compositionstart';
});
// Add editor specific CSS styles
if (self.contentStyles.length > 0) {
contentCssText = '';
each(self.contentStyles, function(style) {
contentCssText += style + "\r\n";
});
self.dom.addStyle(contentCssText);
}
// Load specified content CSS last
each(self.contentCSS, function(cssUrl) {
if (!self.loadedCSS[cssUrl]) {
self.dom.loadCSS(cssUrl);
self.loadedCSS[cssUrl] = true;
}
});
// Handle auto focus
if (settings.auto_focus) {
Delay.setEditorTimeout(self, function() {
var editor;
if (settings.auto_focus === true) {
editor = self;
} else {
editor = self.editorManager.get(settings.auto_focus);
}
if (!editor.destroyed) {
editor.focus();
}
}, 100);
}
// Clean up references for IE
targetElm = doc = body = null;
},
/**
* Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection
* it will also place DOM focus inside the editor.
*
* @method focus
* @param {Boolean} skipFocus Skip DOM focus. Just set is as the active editor.
*/
focus: function(skipFocus) {
var self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng;
var controlElm, doc = self.getDoc(), body = self.getBody(), contentEditableHost;
function getContentEditableHost(node) {
return self.dom.getParent(node, function(node) {
return self.dom.getContentEditable(node) === "true";
});
}
if (!skipFocus) {
// Get selected control element
rng = selection.getRng();
if (rng.item) {
controlElm = rng.item(0);
}
self.quirks.refreshContentEditable();
// Move focus to contentEditable=true child if needed
contentEditableHost = getContentEditableHost(selection.getNode());
if (self.$.contains(body, contentEditableHost)) {
contentEditableHost.focus();
selection.normalize();
self.editorManager.setActive(self);
return;
}
// Focus the window iframe
if (!contentEditable) {
// WebKit needs this call to fire focusin event properly see #5948
// But Opera pre Blink engine will produce an empty selection so skip Opera
if (!Env.opera) {
self.getBody().focus();
}
self.getWin().focus();
}
// Focus the body as well since it's contentEditable
if (isGecko || contentEditable) {
// Check for setActive since it doesn't scroll to the element
if (body.setActive) {
// IE 11 sometimes throws "Invalid function" then fallback to focus
try {
body.setActive();
} catch (ex) {
body.focus();
}
} else {
body.focus();
}
if (contentEditable) {
selection.normalize();
}
}
// Restore selected control element
// This is needed when for example an image is selected within a
// layer a call to focus will then remove the control selection
if (controlElm && controlElm.ownerDocument == doc) {
rng = doc.body.createControlRange();
rng.addElement(controlElm);
rng.select();
}
}
self.editorManager.setActive(self);
},
/**
* Executes a legacy callback. This method is useful to call old 2.x option callbacks.
* There new event model is a better way to add callback so this method might be removed in the future.
*
* @method execCallback
* @param {String} name Name of the callback to execute.
* @return {Object} Return value passed from callback function.
*/
execCallback: function(name) {
var self = this, callback = self.settings[name], scope;
if (!callback) {
return;
}
// Look through lookup
if (self.callbackLookup && (scope = self.callbackLookup[name])) {
callback = scope.func;
scope = scope.scope;
}
if (typeof callback === 'string') {
scope = callback.replace(/\.\w+$/, '');
scope = scope ? resolve(scope) : 0;
callback = resolve(callback);
self.callbackLookup = self.callbackLookup || {};
self.callbackLookup[name] = {func: callback, scope: scope};
}
return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
},
/**
* Translates the specified string by replacing variables with language pack items it will also check if there is
* a key matching the input.
*
* @method translate
* @param {String} text String to translate by the language pack data.
* @return {String} Translated string.
*/
translate: function(text) {
var lang = this.settings.language || 'en', i18n = this.editorManager.i18n;
if (!text) {
return '';
}
text = i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) {
return i18n.data[lang + '.' + b] || '{#' + b + '}';
});
return this.editorManager.translate(text);
},
/**
* Returns a language pack item by name/key.
*
* @method getLang
* @param {String} name Name/key to get from the language pack.
* @param {String} defaultVal Optional default value to retrieve.
*/
getLang: function(name, defaultVal) {
return (
this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] ||
(defaultVal !== undefined ? defaultVal : '{#' + name + '}')
);
},
/**
* Returns a configuration parameter by name.
*
* @method getParam
* @param {String} name Configruation parameter to retrieve.
* @param {String} defaultVal Optional default value to return.
* @param {String} type Optional type parameter.
* @return {String} Configuration parameter value or default value.
* @example
* // Returns a specific config value from the currently active editor
* var someval = tinymce.activeEditor.getParam('myvalue');
*
* // Returns a specific config value from a specific editor instance by id
* var someval2 = tinymce.get('my_editor').getParam('myvalue');
*/
getParam: function(name, defaultVal, type) {
var value = name in this.settings ? this.settings[name] : defaultVal, output;
if (type === 'hash') {
output = {};
if (typeof value === 'string') {
each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) {
value = value.split('=');
if (value.length > 1) {
output[trim(value[0])] = trim(value[1]);
} else {
output[trim(value[0])] = trim(value);
}
});
} else {
output = value;
}
return output;
}
return value;
},
/**
* Dispatches out a onNodeChange event to all observers. This method should be called when you
* need to update the UI states or element path etc.
*
* @method nodeChanged
* @param {Object} args Optional args to pass to NodeChange event handlers.
*/
nodeChanged: function(args) {
this._nodeChangeDispatcher.nodeChanged(args);
},
/**
* Adds a button that later gets created by the theme in the editors toolbars.
*
* @method addButton
* @param {String} name Button name to add.
* @param {Object} settings Settings object with title, cmd etc.
* @example
* // Adds a custom button to the editor that inserts contents when clicked
* tinymce.init({
* ...
*
* toolbar: 'example'
*
* setup: function(ed) {
* ed.addButton('example', {
* title: 'My title',
* image: '../js/tinymce/plugins/example/img/example.gif',
* onclick: function() {
* ed.insertContent('Hello world!!');
* }
* });
* }
* });
*/
addButton: function(name, settings) {
var self = this;
if (settings.cmd) {
settings.onclick = function() {
self.execCommand(settings.cmd);
};
}
if (!settings.text && !settings.icon) {
settings.icon = name;
}
self.buttons = self.buttons || {};
settings.tooltip = settings.tooltip || settings.title;
self.buttons[name] = settings;
},
/**
* Adds a menu item to be used in the menus of the theme. There might be multiple instances
* of this menu item for example it might be used in the main menus of the theme but also in
* the context menu so make sure that it's self contained and supports multiple instances.
*
* @method addMenuItem
* @param {String} name Menu item name to add.
* @param {Object} settings Settings object with title, cmd etc.
* @example
* // Adds a custom menu item to the editor that inserts contents when clicked
* // The context option allows you to add the menu item to an existing default menu
* tinymce.init({
* ...
*
* setup: function(ed) {
* ed.addMenuItem('example', {
* text: 'My menu item',
* context: 'tools',
* onclick: function() {
* ed.insertContent('Hello world!!');
* }
* });
* }
* });
*/
addMenuItem: function(name, settings) {
var self = this;
if (settings.cmd) {
settings.onclick = function() {
self.execCommand(settings.cmd);
};
}
self.menuItems = self.menuItems || {};
self.menuItems[name] = settings;
},
/**
* Adds a contextual toolbar to be rendered when the selector matches.
*
* @method addContextToolbar
* @param {function/string} predicate Predicate that needs to return true if provided strings get converted into CSS predicates.
* @param {String/Array} items String or array with items to add to the context toolbar.
*/
addContextToolbar: function(predicate, items) {
var self = this, selector;
self.contextToolbars = self.contextToolbars || [];
// Convert selector to predicate
if (typeof predicate == "string") {
selector = predicate;
predicate = function(elm) {
return self.dom.is(elm, selector);
};
}
self.contextToolbars.push({
id: Uuid.uuid('mcet'),
predicate: predicate,
items: items
});
},
/**
* Adds a custom command to the editor, you can also override existing commands with this method.
* The command that you add can be executed with execCommand.
*
* @method addCommand
* @param {String} name Command name to add/override.
* @param {addCommandCallback} callback Function to execute when the command occurs.
* @param {Object} scope Optional scope to execute the function in.
* @example
* // Adds a custom command that later can be executed using execCommand
* tinymce.init({
* ...
*
* setup: function(ed) {
* // Register example command
* ed.addCommand('mycommand', function(ui, v) {
* ed.windowManager.alert('Hello world!! Selection: ' + ed.selection.getContent({format: 'text'}));
* });
* }
* });
*/
addCommand: function(name, callback, scope) {
/**
* Callback function that gets called when a command is executed.
*
* @callback addCommandCallback
* @param {Boolean} ui Display UI state true/false.
* @param {Object} value Optional value for command.
* @return {Boolean} True/false state if the command was handled or not.
*/
this.editorCommands.addCommand(name, callback, scope);
},
/**
* Adds a custom query state command to the editor, you can also override existing commands with this method.
* The command that you add can be executed with queryCommandState function.
*
* @method addQueryStateHandler
* @param {String} name Command name to add/override.
* @param {addQueryStateHandlerCallback} callback Function to execute when the command state retrieval occurs.
* @param {Object} scope Optional scope to execute the function in.
*/
addQueryStateHandler: function(name, callback, scope) {
/**
* Callback function that gets called when a queryCommandState is executed.
*
* @callback addQueryStateHandlerCallback
* @return {Boolean} True/false state if the command is enabled or not like is it bold.
*/
this.editorCommands.addQueryStateHandler(name, callback, scope);
},
/**
* Adds a custom query value command to the editor, you can also override existing commands with this method.
* The command that you add can be executed with queryCommandValue function.
*
* @method addQueryValueHandler
* @param {String} name Command name to add/override.
* @param {addQueryValueHandlerCallback} callback Function to execute when the command value retrieval occurs.
* @param {Object} scope Optional scope to execute the function in.
*/
addQueryValueHandler: function(name, callback, scope) {
/**
* Callback function that gets called when a queryCommandValue is executed.
*
* @callback addQueryValueHandlerCallback
* @return {Object} Value of the command or undefined.
*/
this.editorCommands.addQueryValueHandler(name, callback, scope);
},
/**
* Adds a keyboard shortcut for some command or function.
*
* @method addShortcut
* @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o.
* @param {String} desc Text description for the command.
* @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed.
* @param {Object} sc Optional scope to execute the function in.
* @return {Boolean} true/false state if the shortcut was added or not.
*/
addShortcut: function(pattern, desc, cmdFunc, scope) {
this.shortcuts.add(pattern, desc, cmdFunc, scope);
},
/**
* Executes a command on the current instance. These commands can be TinyMCE internal commands prefixed with "mce" or
* they can be build in browser commands such as "Bold". A compleate list of browser commands is available on MSDN or Mozilla.org.
* This function will dispatch the execCommand function on each plugin, theme or the execcommand_callback option if none of these
* return true it will handle the command as a internal browser command.
*
* @method execCommand
* @param {String} cmd Command name to execute, for example mceLink or Bold.
* @param {Boolean} ui True/false state if a UI (dialog) should be presented or not.
* @param {mixed} value Optional command value, this can be anything.
* @param {Object} args Optional arguments object.
*/
execCommand: function(cmd, ui, value, args) {
return this.editorCommands.execCommand(cmd, ui, value, args);
},
/**
* Returns a command specific state, for example if bold is enabled or not.
*
* @method queryCommandState
* @param {string} cmd Command to query state from.
* @return {Boolean} Command specific state, for example if bold is enabled or not.
*/
queryCommandState: function(cmd) {
return this.editorCommands.queryCommandState(cmd);
},
/**
* Returns a command specific value, for example the current font size.
*
* @method queryCommandValue
* @param {string} cmd Command to query value from.
* @return {Object} Command specific value, for example the current font size.
*/
queryCommandValue: function(cmd) {
return this.editorCommands.queryCommandValue(cmd);
},
/**
* Returns true/false if the command is supported or not.
*
* @method queryCommandSupported
* @param {String} cmd Command that we check support for.
* @return {Boolean} true/false if the command is supported or not.
*/
queryCommandSupported: function(cmd) {
return this.editorCommands.queryCommandSupported(cmd);
},
/**
* Shows the editor and hides any textarea/div that the editor is supposed to replace.
*
* @method show
*/
show: function() {
var self = this;
if (self.hidden) {
self.hidden = false;
if (self.inline) {
self.getBody().contentEditable = true;
} else {
DOM.show(self.getContainer());
DOM.hide(self.id);
}
self.load();
self.fire('show');
}
},
/**
* Hides the editor and shows any textarea/div that the editor is supposed to replace.
*
* @method hide
*/
hide: function() {
var self = this, doc = self.getDoc();
if (!self.hidden) {
// Fixed bug where IE has a blinking cursor left from the editor
if (ie && doc && !self.inline) {
doc.execCommand('SelectAll');
}
// We must save before we hide so Safari doesn't crash
self.save();
if (self.inline) {
self.getBody().contentEditable = false;
// Make sure the editor gets blurred
if (self == self.editorManager.focusedEditor) {
self.editorManager.focusedEditor = null;
}
} else {
DOM.hide(self.getContainer());
DOM.setStyle(self.id, 'display', self.orgDisplay);
}
self.hidden = true;
self.fire('hide');
}
},
/**
* Returns true/false if the editor is hidden or not.
*
* @method isHidden
* @return {Boolean} True/false if the editor is hidden or not.
*/
isHidden: function() {
return !!this.hidden;
},
/**
* Sets the progress state, this will display a throbber/progess for the editor.
* This is ideal for asynchronous operations like an AJAX save call.
*
* @method setProgressState
* @param {Boolean} state Boolean state if the progress should be shown or hidden.
* @param {Number} time Optional time to wait before the progress gets shown.
* @return {Boolean} Same as the input state.
* @example
* // Show progress for the active editor
* tinymce.activeEditor.setProgressState(true);
*
* // Hide progress for the active editor
* tinymce.activeEditor.setProgressState(false);
*
* // Show progress after 3 seconds
* tinymce.activeEditor.setProgressState(true, 3000);
*/
setProgressState: function(state, time) {
this.fire('ProgressState', {state: state, time: time});
},
/**
* Loads contents from the textarea or div element that got converted into an editor instance.
* This method will move the contents from that textarea or div into the editor by using setContent
* so all events etc that method has will get dispatched as well.
*
* @method load
* @param {Object} args Optional content object, this gets passed around through the whole load process.
* @return {String} HTML string that got set into the editor.
*/
load: function(args) {
var self = this, elm = self.getElement(), html;
if (elm) {
args = args || {};
args.load = true;
html = self.setContent(elm.value !== undefined ? elm.value : elm.innerHTML, args);
args.element = elm;
if (!args.no_events) {
self.fire('LoadContent', args);
}
args.element = elm = null;
return html;
}
},
/**
* Saves the contents from a editor out to the textarea or div element that got converted into an editor instance.
* This method will move the HTML contents from the editor into that textarea or div by getContent
* so all events etc that method has will get dispatched as well.
*
* @method save
* @param {Object} args Optional content object, this gets passed around through the whole save process.
* @return {String} HTML string that got set into the textarea/div.
*/
save: function(args) {
var self = this, elm = self.getElement(), html, form;
if (!elm || !self.initialized) {
return;
}
args = args || {};
args.save = true;
args.element = elm;
html = args.content = self.getContent(args);
if (!args.no_events) {
self.fire('SaveContent', args);
}
// Always run this internal event
if (args.format == 'raw') {
self.fire('RawSaveContent', args);
}
html = args.content;
if (!/TEXTAREA|INPUT/i.test(elm.nodeName)) {
// Update DIV element when not in inline mode
if (!self.inline) {
elm.innerHTML = html;
}
// Update hidden form element
if ((form = DOM.getParent(self.id, 'form'))) {
each(form.elements, function(elm) {
if (elm.name == self.id) {
elm.value = html;
return false;
}
});
}
} else {
elm.value = html;
}
args.element = elm = null;
if (args.set_dirty !== false) {
self.setDirty(false);
}
return html;
},
/**
* Sets the specified content to the editor instance, this will cleanup the content before it gets set using
* the different cleanup rules options.
*
* @method setContent
* @param {String} content Content to set to editor, normally HTML contents but can be other formats as well.
* @param {Object} args Optional content object, this gets passed around through the whole set process.
* @return {String} HTML string that got set into the editor.
* @example
* // Sets the HTML contents of the activeEditor editor
* tinymce.activeEditor.setContent('<span>some</span> html');
*
* // Sets the raw contents of the activeEditor editor
* tinymce.activeEditor.setContent('<span>some</span> html', {format: 'raw'});
*
* // Sets the content of a specific editor (my_editor in this example)
* tinymce.get('my_editor').setContent(data);
*
* // Sets the bbcode contents of the activeEditor editor if the bbcode plugin was added
* tinymce.activeEditor.setContent('[b]some[/b] html', {format: 'bbcode'});
*/
setContent: function(content, args) {
var self = this, body = self.getBody(), forcedRootBlockName, padd;
// Setup args object
args = args || {};
args.format = args.format || 'html';
args.set = true;
args.content = content;
// Do preprocessing
if (!args.no_events) {
self.fire('BeforeSetContent', args);
}
content = args.content;
// Padd empty content in Gecko and Safari. Commands will otherwise fail on the content
// It will also be impossible to place the caret in the editor unless there is a BR element present
if (content.length === 0 || /^\s+$/.test(content)) {
padd = ie && ie < 11 ? '' : '<br data-mce-bogus="1">';
// Todo: There is a lot more root elements that need special padding
// so separate this and add all of them at some point.
if (body.nodeName == 'TABLE') {
content = '<tr><td>' + padd + '</td></tr>';
} else if (/^(UL|OL)$/.test(body.nodeName)) {
content = '<li>' + padd + '</li>';
}
forcedRootBlockName = self.settings.forced_root_block;
// Check if forcedRootBlock is configured and that the block is a valid child of the body
if (forcedRootBlockName && self.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
// Padd with bogus BR elements on modern browsers and IE 7 and 8 since they don't render empty P tags properly
content = padd;
content = self.dom.createHTML(forcedRootBlockName, self.settings.forced_root_block_attrs, content);
} else if (!ie && !content) {
// We need to add a BR when forced_root_block is disabled on non IE browsers to place the caret
content = '<br data-mce-bogus="1">';
}
self.dom.setHTML(body, content);
self.fire('SetContent', args);
} else {
// Parse and serialize the html
if (args.format !== 'raw') {
content = new Serializer({
validate: self.validate
}, self.schema).serialize(
self.parser.parse(content, {isRootContent: true})
);
}
// Set the new cleaned contents to the editor
args.content = trim(content);
self.dom.setHTML(body, args.content);
// Do post processing
if (!args.no_events) {
self.fire('SetContent', args);
}
// Don't normalize selection if the focused element isn't the body in
// content editable mode since it will steal focus otherwise
/*if (!self.settings.content_editable || document.activeElement === self.getBody()) {
self.selection.normalize();
}*/
}
return args.content;
},
/**
* Gets the content from the editor instance, this will cleanup the content before it gets returned using
* the different cleanup rules options.
*
* @method getContent
* @param {Object} args Optional content object, this gets passed around through the whole get process.
* @return {String} Cleaned content string, normally HTML contents.
* @example
* // Get the HTML contents of the currently active editor
* console.debug(tinymce.activeEditor.getContent());
*
* // Get the raw contents of the currently active editor
* tinymce.activeEditor.getContent({format: 'raw'});
*
* // Get content of a specific editor:
* tinymce.get('content id').getContent()
*/
getContent: function(args) {
var self = this, content, body = self.getBody();
// Setup args object
args = args || {};
args.format = args.format || 'html';
args.get = true;
args.getInner = true;
// Do preprocessing
if (!args.no_events) {
self.fire('BeforeGetContent', args);
}
// Get raw contents or by default the cleaned contents
if (args.format == 'raw') {
content = self.serializer.getTrimmedContent();
} else if (args.format == 'text') {
content = body.innerText || body.textContent;
} else {
content = self.serializer.serialize(body, args);
}
// Trim whitespace in beginning/end of HTML
if (args.format != 'text') {
args.content = trim(content);
} else {
args.content = content;
}
// Do post processing
if (!args.no_events) {
self.fire('GetContent', args);
}
return args.content;
},
/**
* Inserts content at caret position.
*
* @method insertContent
* @param {String} content Content to insert.
* @param {Object} args Optional args to pass to insert call.
*/
insertContent: function(content, args) {
if (args) {
content = extend({content: content}, args);
}
this.execCommand('mceInsertContent', false, content);
},
/**
* Returns true/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents.
*
* The dirty state is automatically set to true if you do modifications to the content in other
* words when new undo levels is created or if you undo/redo to update the contents of the editor. It will also be set
* to false if you call editor.save().
*
* @method isDirty
* @return {Boolean} True/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents.
* @example
* if (tinymce.activeEditor.isDirty())
* alert("You must save your contents.");
*/
isDirty: function() {
return !this.isNotDirty;
},
/**
* Explicitly sets the dirty state. This will fire the dirty event if the editor dirty state is changed from false to true
* by invoking this method.
*
* @method setDirty
* @param {Boolean} state True/false if the editor is considered dirty.
* @example
* function ajaxSave() {
* var editor = tinymce.get('elm1');
*
* // Save contents using some XHR call
* alert(editor.getContent());
*
* editor.setDirty(false); // Force not dirty state
* }
*/
setDirty: function(state) {
var oldState = !this.isNotDirty;
this.isNotDirty = !state;
if (state && state != oldState) {
this.fire('dirty');
}
},
/**
* Sets the editor mode. Mode can be for example "design", "code" or "readonly".
*
* @method setMode
* @param {String} mode Mode to set the editor in.
*/
setMode: function(mode) {
Mode.setMode(this, mode);
},
/**
* Returns the editors container element. The container element wrappes in
* all the elements added to the page for the editor. Such as UI, iframe etc.
*
* @method getContainer
* @return {Element} HTML DOM element for the editor container.
*/
getContainer: function() {
var self = this;
if (!self.container) {
self.container = DOM.get(self.editorContainer || self.id + '_parent');
}
return self.container;
},
/**
* Returns the editors content area container element. The this element is the one who
* holds the iframe or the editable element.
*
* @method getContentAreaContainer
* @return {Element} HTML DOM element for the editor area container.
*/
getContentAreaContainer: function() {
return this.contentAreaContainer;
},
/**
* Returns the target element/textarea that got replaced with a TinyMCE editor instance.
*
* @method getElement
* @return {Element} HTML DOM element for the replaced element.
*/
getElement: function() {
if (!this.targetElm) {
this.targetElm = DOM.get(this.id);
}
return this.targetElm;
},
/**
* Returns the iframes window object.
*
* @method getWin
* @return {Window} Iframe DOM window object.
*/
getWin: function() {
var self = this, elm;
if (!self.contentWindow) {
elm = self.iframeElement;
if (elm) {
self.contentWindow = elm.contentWindow;
}
}
return self.contentWindow;
},
/**
* Returns the iframes document object.
*
* @method getDoc
* @return {Document} Iframe DOM document object.
*/
getDoc: function() {
var self = this, win;
if (!self.contentDocument) {
win = self.getWin();
if (win) {
self.contentDocument = win.document;
}
}
return self.contentDocument;
},
/**
* Returns the root element of the editable area.
* For a non-inline iframe-based editor, returns the iframe's body element.
*
* @method getBody
* @return {Element} The root element of the editable area.
*/
getBody: function() {
var doc = this.getDoc();
return this.bodyElement || (doc ? doc.body : null);
},
/**
* URL converter function this gets executed each time a user adds an img, a or
* any other element that has a URL in it. This will be called both by the DOM and HTML
* manipulation functions.
*
* @method convertURL
* @param {string} url URL to convert.
* @param {string} name Attribute name src, href etc.
* @param {string/HTMLElement} elm Tag name or HTML DOM element depending on HTML or DOM insert.
* @return {string} Converted URL string.
*/
convertURL: function(url, name, elm) {
var self = this, settings = self.settings;
// Use callback instead
if (settings.urlconverter_callback) {
return self.execCallback('urlconverter_callback', url, elm, true, name);
}
// Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs
if (!settings.convert_urls || (elm && elm.nodeName == 'LINK') || url.indexOf('file:') === 0 || url.length === 0) {
return url;
}
// Convert to relative
if (settings.relative_urls) {
return self.documentBaseURI.toRelative(url);
}
// Convert to absolute
url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
return url;
},
/**
* Adds visual aid for tables, anchors etc so they can be more easily edited inside the editor.
*
* @method addVisual
* @param {Element} elm Optional root element to loop though to find tables etc that needs the visual aid.
*/
addVisual: function(elm) {
var self = this, settings = self.settings, dom = self.dom, cls;
elm = elm || self.getBody();
if (self.hasVisual === undefined) {
self.hasVisual = settings.visual;
}
each(dom.select('table,a', elm), function(elm) {
var value;
switch (elm.nodeName) {
case 'TABLE':
cls = settings.visual_table_class || 'mce-item-table';
value = dom.getAttrib(elm, 'border');
if ((!value || value == '0') && self.hasVisual) {
dom.addClass(elm, cls);
} else {
dom.removeClass(elm, cls);
}
return;
case 'A':
if (!dom.getAttrib(elm, 'href', false)) {
value = dom.getAttrib(elm, 'name') || elm.id;
cls = settings.visual_anchor_class || 'mce-item-anchor';
if (value && self.hasVisual) {
dom.addClass(elm, cls);
} else {
dom.removeClass(elm, cls);
}
}
return;
}
});
self.fire('VisualAid', {element: elm, hasVisual: self.hasVisual});
},
/**
* Removes the editor from the dom and tinymce collection.
*
* @method remove
*/
remove: function() {
var self = this;
if (!self.removed) {
self.save();
self.removed = 1;
self.unbindAllNativeEvents();
// Remove any hidden input
if (self.hasHiddenInput) {
DOM.remove(self.getElement().nextSibling);
}
if (!self.inline) {
// IE 9 has a bug where the selection stops working if you place the
// caret inside the editor then remove the iframe
if (ie && ie < 10) {
self.getDoc().execCommand('SelectAll', false, null);
}
DOM.setStyle(self.id, 'display', self.orgDisplay);
self.getBody().onload = null; // Prevent #6816
}
self.fire('remove');
self.editorManager.remove(self);
DOM.remove(self.getContainer());
self._selectionOverrides.destroy();
self.editorUpload.destroy();
self.destroy();
}
},
/**
* Destroys the editor instance by removing all events, element references or other resources
* that could leak memory. This method will be called automatically when the page is unloaded
* but you can also call it directly if you know what you are doing.
*
* @method destroy
* @param {Boolean} automatic Optional state if the destroy is an automatic destroy or user called one.
*/
destroy: function(automatic) {
var self = this, form;
// One time is enough
if (self.destroyed) {
return;
}
// If user manually calls destroy and not remove
// Users seems to have logic that calls destroy instead of remove
if (!automatic && !self.removed) {
self.remove();
return;
}
if (!automatic) {
self.editorManager.off('beforeunload', self._beforeUnload);
// Manual destroy
if (self.theme && self.theme.destroy) {
self.theme.destroy();
}
// Destroy controls, selection and dom
self.selection.destroy();
self.dom.destroy();
}
form = self.formElement;
if (form) {
if (form._mceOldSubmit) {
form.submit = form._mceOldSubmit;
form._mceOldSubmit = null;
}
DOM.unbind(form, 'submit reset', self.formEventDelegate);
}
self.contentAreaContainer = self.formElement = self.container = self.editorContainer = null;
self.bodyElement = self.contentDocument = self.contentWindow = null;
self.iframeElement = self.targetElm = null;
if (self.selection) {
self.selection = self.selection.win = self.selection.dom = self.selection.dom.doc = null;
}
self.destroyed = 1;
},
/**
* Uploads all data uri/blob uri images in the editor contents to server.
*
* @method uploadImages
* @param {function} callback Optional callback with images and status for each image.
* @return {tinymce.util.Promise} Promise instance.
*/
uploadImages: function(callback) {
return this.editorUpload.uploadImages(callback);
},
// Internal functions
_scanForImages: function() {
return this.editorUpload.scanForImages();
}
};
extend(Editor.prototype, EditorObservable);
return Editor;
});