Debian Codegraph @

dijit/_editor/RichText.js

raw symbols SCIP
1 define([
2 "dojo/_base/array", // array.forEach array.indexOf array.some
3 "dojo/_base/config", // config
4 "dojo/_base/declare", // declare
5 "dojo/_base/Deferred", // Deferred
6 "dojo/dom", // dom.byId
7 "dojo/dom-attr", // domAttr.set or get
8 "dojo/dom-class", // domClass.add domClass.remove
9 "dojo/dom-construct", // domConstruct.create domConstruct.destroy domConstruct.place
10 "dojo/dom-geometry", // domGeometry.position
11 "dojo/dom-style", // domStyle.getComputedStyle domStyle.set
12 "dojo/_base/kernel", // kernel.deprecated, kernel.locale
13 "dojo/keys", // keys.BACKSPACE keys.TAB
14 "dojo/_base/lang", // lang.clone lang.hitch lang.isArray lang.isFunction lang.isString lang.trim
15 "dojo/on", // on()
16 "dojo/query", // query
17 "dojo/domReady",
18 "dojo/sniff", // has("ie") has("mozilla") has("opera") has("safari") has("webkit")
19 "dojo/string",
20 "dojo/topic", // topic.publish() (publish)
21 "dojo/_base/unload", // unload
22 "dojo/_base/url", // url
23 "dojo/window", // winUtils.get()
24 "../_Widget",
25 "../_CssStateMixin",
26 "../selection",
27 "./range",
28 "./html",
29 "../focus",
30 "../main" // dijit._scopeName
31 ], function(array, config, declare, Deferred, dom, domAttr, domClass, domConstruct, domGeometry, domStyle,
32 kernel, keys, lang, on, query, domReady, has, string, topic, unload, _Url, winUtils,
33 _Widget, _CssStateMixin, selectionapi, rangeapi, htmlapi, focus, dijit){
34
35 // module:
36 // dijit/_editor/RichText
37
38 // If you want to allow for rich text saving with back/forward actions, you must add a text area to your page with
39 // the id==dijit._scopeName + "._editor.RichText.value" (typically "dijit/_editor/RichText.value). For example,
40 // something like this will work:
41 //
42 // <textarea id="dijit._editor.RichText.value" style="display:none;position:absolute;top:-100px;left:-100px;height:3px;width:3px;overflow:hidden;"></textarea>
43
44 var RichText = declare("dijit._editor.RichText", [_Widget, _CssStateMixin], {
45 // summary:
46 // dijit/_editor/RichText is the core of dijit.Editor, which provides basic
47 // WYSIWYG editing features.
48 //
49 // description:
50 // dijit/_editor/RichText is the core of dijit.Editor, which provides basic
51 // WYSIWYG editing features. It also encapsulates the differences
52 // of different js engines for various browsers. Do not use this widget
53 // with an HTML &lt;TEXTAREA&gt; tag, since the browser unescapes XML escape characters,
54 // like &lt;. This can have unexpected behavior and lead to security issues
55 // such as scripting attacks.
56 //
57 // tags:
58 // private
59
60 constructor: function(params /*===== , srcNodeRef =====*/){
61 // summary:
62 // Create the widget.
63 // params: Object|null
64 // Initial settings for any of the widget attributes, except readonly attributes.
65 // srcNodeRef: DOMNode
66 // The widget replaces the specified DOMNode.
67
68 // contentPreFilters: Function(String)[]
69 // Pre content filter function register array.
70 // these filters will be executed before the actual
71 // editing area gets the html content.
72 this.contentPreFilters = [];
73
74 // contentPostFilters: Function(String)[]
75 // post content filter function register array.
76 // These will be used on the resulting html
77 // from contentDomPostFilters. The resulting
78 // content is the final html (returned by getValue()).
79 this.contentPostFilters = [];
80
81 // contentDomPreFilters: Function(DomNode)[]
82 // Pre content dom filter function register array.
83 // These filters are applied after the result from
84 // contentPreFilters are set to the editing area.
85 this.contentDomPreFilters = [];
86
87 // contentDomPostFilters: Function(DomNode)[]
88 // Post content dom filter function register array.
89 // These filters are executed on the editing area dom.
90 // The result from these will be passed to contentPostFilters.
91 this.contentDomPostFilters = [];
92
93 // editingAreaStyleSheets: dojo._URL[]
94 // array to store all the stylesheets applied to the editing area
95 this.editingAreaStyleSheets = [];
96
97 // Make a copy of this.events before we start writing into it, otherwise we
98 // will modify the prototype which leads to bad things on pages w/multiple editors
99 this.events = [].concat(this.events);
100
101 this._keyHandlers = {};
102
103 if(params && lang.isString(params.value)){
104 this.value = params.value;
105 }
106
107 this.onLoadDeferred = new Deferred();
108 },
109
110 baseClass: "dijitEditor",
111
112 // inheritWidth: Boolean
113 // whether to inherit the parent's width or simply use 100%
114 inheritWidth: false,
115
116 // focusOnLoad: [deprecated] Boolean
117 // Focus into this widget when the page is loaded
118 focusOnLoad: false,
119
120 // name: String?
121 // Specifies the name of a (hidden) `<textarea>` node on the page that's used to save
122 // the editor content on page leave. Used to restore editor contents after navigating
123 // to a new page and then hitting the back button.
124 name: "",
125
126 // styleSheets: [const] String
127 // semicolon (";") separated list of css files for the editing area
128 styleSheets: "",
129
130 // height: String
131 // Set height to fix the editor at a specific height, with scrolling.
132 // By default, this is 300px. If you want to have the editor always
133 // resizes to accommodate the content, use AlwaysShowToolbar plugin
134 // and set height="". If this editor is used within a layout widget,
135 // set height="100%".
136 height: "300px",
137
138 // minHeight: String
139 // The minimum height that the editor should have.
140 minHeight: "1em",
141
142 // isClosed: [private] Boolean
143 isClosed: true,
144
145 // isLoaded: [private] Boolean
146 isLoaded: false,
147
148 // _SEPARATOR: [private] String
149 // Used to concat contents from multiple editors into a single string,
150 // so they can be saved into a single `<textarea>` node. See "name" attribute.
151 _SEPARATOR: "@@**%%__RICHTEXTBOUNDRY__%%**@@",
152
153 // _NAME_CONTENT_SEP: [private] String
154 // USed to separate name from content. Just a colon isn't safe.
155 _NAME_CONTENT_SEP: "@@**%%:%%**@@",
156
157 // onLoadDeferred: [readonly] dojo/promise/Promise
158 // Deferred which is fired when the editor finishes loading.
159 // Call myEditor.onLoadDeferred.then(callback) it to be informed
160 // when the rich-text area initialization is finalized.
161 onLoadDeferred: null,
162
163 // isTabIndent: Boolean
164 // Make tab key and shift-tab indent and outdent rather than navigating.
165 // Caution: sing this makes web pages inaccessible to users unable to use a mouse.
166 isTabIndent: false,
167
168 // disableSpellCheck: [const] Boolean
169 // When true, disables the browser's native spell checking, if supported.
170 // Works only in Firefox.
171 disableSpellCheck: false,
172
173 postCreate: function(){
174 if("textarea" === this.domNode.tagName.toLowerCase()){
175 console.warn("RichText should not be used with the TEXTAREA tag. See dijit._editor.RichText docs.");
176 }
177
178 // Push in the builtin filters now, making them the first executed, but not over-riding anything
179 // users passed in. See: #6062
180 this.contentPreFilters = [
181 lang.trim, // avoid IE10 problem hitting ENTER on last line when there's a trailing \n.
182 lang.hitch(this, "_preFixUrlAttributes")
183 ].concat(this.contentPreFilters);
184 if(has("mozilla")){
185 this.contentPreFilters = [this._normalizeFontStyle].concat(this.contentPreFilters);
186 this.contentPostFilters = [this._removeMozBogus].concat(this.contentPostFilters);
187 }
188 if(has("webkit")){
189 // Try to clean up WebKit bogus artifacts. The inserted classes
190 // made by WebKit sometimes messes things up.
191 this.contentPreFilters = [this._removeWebkitBogus].concat(this.contentPreFilters);
192 this.contentPostFilters = [this._removeWebkitBogus].concat(this.contentPostFilters);
193 }
194 if(has("ie") || has("trident")){
195 // IE generates <strong> and <em> but we want to normalize to <b> and <i>
196 // Still happens in IE11, but doesn't happen with Edge.
197 this.contentPostFilters = [this._normalizeFontStyle].concat(this.contentPostFilters);
198 this.contentDomPostFilters = [lang.hitch(this, "_stripBreakerNodes")].concat(this.contentDomPostFilters);
199 }
200 this.contentDomPostFilters = [lang.hitch(this, "_stripTrailingEmptyNodes")].concat(this.contentDomPostFilters);
201 this.inherited(arguments);
202
203 topic.publish(dijit._scopeName + "._editor.RichText::init", this);
204 },
205
206 startup: function(){
207 this.inherited(arguments);
208
209 // Don't call open() until startup() because we need to be attached to the DOM, and also if we are the
210 // child of a StackContainer, let StackContainer._setupChild() do DOM manipulations before iframe is
211 // created, to avoid duplicate onload call.
212 this.open();
213 this.setupDefaultShortcuts();
214 },
215
216 setupDefaultShortcuts: function(){
217 // summary:
218 // Add some default key handlers
219 // description:
220 // Overwrite this to setup your own handlers. The default
221 // implementation does not use Editor commands, but directly
222 // executes the builtin commands within the underlying browser
223 // support.
224 // tags:
225 // protected
226 var exec = lang.hitch(this, function(cmd, arg){
227 return function(){
228 return !this.execCommand(cmd, arg);
229 };
230 });
231
232 var ctrlKeyHandlers = {
233 b: exec("bold"),
234 i: exec("italic"),
235 u: exec("underline"),
236 a: exec("selectall"),
237 s: function(){
238 this.save(true);
239 },
240 m: function(){
241 this.isTabIndent = !this.isTabIndent;
242 },
243
244 "1": exec("formatblock", "h1"),
245 "2": exec("formatblock", "h2"),
246 "3": exec("formatblock", "h3"),
247 "4": exec("formatblock", "h4"),
248
249 "\\": exec("insertunorderedlist")
250 };
251
252 if(!has("ie")){
253 ctrlKeyHandlers.Z = exec("redo"); //FIXME: undo?
254 }
255
256 var key;
257 for(key in ctrlKeyHandlers){
258 this.addKeyHandler(key, true, false, ctrlKeyHandlers[key]);
259 }
260 },
261
262 // events: [private] String[]
263 // events which should be connected to the underlying editing area
264 events: ["onKeyDown", "onKeyUp"], // onClick handled specially
265
266 // captureEvents: [deprecated] String[]
267 // Events which should be connected to the underlying editing
268 // area, events in this array will be addListener with
269 // capture=true.
270 // TODO: looking at the code I don't see any distinction between events and captureEvents,
271 // so get rid of this for 2.0 if not sooner
272 captureEvents: [],
273
274 _editorCommandsLocalized: false,
275 _localizeEditorCommands: function(){
276 // summary:
277 // When IE is running in a non-English locale, the API actually changes,
278 // so that we have to say (for example) danraku instead of p (for paragraph).
279 // Handle that here.
280 // tags:
281 // private
282 if(RichText._editorCommandsLocalized){
283 // Use the already generate cache of mappings.
284 this._local2NativeFormatNames = RichText._local2NativeFormatNames;
285 this._native2LocalFormatNames = RichText._native2LocalFormatNames;
286 return;
287 }
288 RichText._editorCommandsLocalized = true;
289 RichText._local2NativeFormatNames = {};
290 RichText._native2LocalFormatNames = {};
291 this._local2NativeFormatNames = RichText._local2NativeFormatNames;
292 this._native2LocalFormatNames = RichText._native2LocalFormatNames;
293 //in IE, names for blockformat is locale dependent, so we cache the values here
294
295 //put p after div, so if IE returns Normal, we show it as paragraph
296 //We can distinguish p and div if IE returns Normal, however, in order to detect that,
297 //we have to call this.document.selection.createRange().parentElement() or such, which
298 //could slow things down. Leave it as it is for now
299 var formats = ['div', 'p', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ol', 'ul', 'address'];
300 var localhtml = "", format, i = 0;
301 while((format = formats[i++])){
302 //append a <br> after each element to separate the elements more reliably
303 if(format.charAt(1) !== 'l'){
304 localhtml += "<" + format + "><span>content</span></" + format + "><br/>";
305 }else{
306 localhtml += "<" + format + "><li>content</li></" + format + "><br/>";
307 }
308 }
309 // queryCommandValue returns empty if we hide editNode, so move it out of screen temporary
310 // Also, IE9 does weird stuff unless we do it inside the editor iframe.
311 var style = { position: "absolute", top: "0px", zIndex: 10, opacity: 0.01 };
312 var div = domConstruct.create('div', {style: style, innerHTML: localhtml});
313 this.ownerDocumentBody.appendChild(div);
314
315 // IE9 has a timing issue with doing this right after setting
316 // the inner HTML, so put a delay in.
317 var inject = lang.hitch(this, function(){
318 var node = div.firstChild;
319 while(node){
320 try{
321 this.selection.selectElement(node.firstChild);
322 var nativename = node.tagName.toLowerCase();
323 this._local2NativeFormatNames[nativename] = document.queryCommandValue("formatblock");
324 this._native2LocalFormatNames[this._local2NativeFormatNames[nativename]] = nativename;
325 node = node.nextSibling.nextSibling;
326 //console.log("Mapped: ", nativename, " to: ", this._local2NativeFormatNames[nativename]);
327 }catch(e){ /*Sqelch the occasional IE9 error */
328 }
329 }
330 domConstruct.destroy(div);
331 });
332 this.defer(inject);
333 },
334
335 open: function(/*DomNode?*/ element){
336 // summary:
337 // Transforms the node referenced in this.domNode into a rich text editing
338 // node.
339 // description:
340 // Sets up the editing area asynchronously. This will result in
341 // the creation and replacement with an iframe.
342 // tags:
343 // private
344
345 if(!this.onLoadDeferred || this.onLoadDeferred.fired >= 0){
346 this.onLoadDeferred = new Deferred();
347 }
348
349 if(!this.isClosed){
350 this.close();
351 }
352 topic.publish(dijit._scopeName + "._editor.RichText::open", this);
353
354 if(arguments.length === 1 && element.nodeName){ // else unchanged
355 this.domNode = element;
356 }
357
358 var dn = this.domNode;
359
360 // Compute initial value of the editor
361 var html;
362 if(lang.isString(this.value)){
363 // Allow setting the editor content programmatically instead of
364 // relying on the initial content being contained within the target
365 // domNode.
366 html = this.value;
367 dn.innerHTML = "";
368 }else if(dn.nodeName && dn.nodeName.toLowerCase() == "textarea"){
369 // if we were created from a textarea, then we need to create a
370 // new editing harness node.
371 var ta = (this.textarea = dn);
372 this.name = ta.name;
373 html = ta.value;
374 dn = this.domNode = this.ownerDocument.createElement("div");
375 dn.setAttribute('widgetId', this.id);
376 ta.removeAttribute('widgetId');
377 dn.cssText = ta.cssText;
378 dn.className += " " + ta.className;
379 domConstruct.place(dn, ta, "before");
380 var tmpFunc = lang.hitch(this, function(){
381 //some browsers refuse to submit display=none textarea, so
382 //move the textarea off screen instead
383 domStyle.set(ta, {
384 display: "block",
385 position: "absolute",
386 top: "-1000px"
387 });
388
389 if(has("ie")){ //nasty IE bug: abnormal formatting if overflow is not hidden
390 var s = ta.style;
391 this.__overflow = s.overflow;
392 s.overflow = "hidden";
393 }
394 });
395 if(has("ie")){
396 this.defer(tmpFunc, 10);
397 }else{
398 tmpFunc();
399 }
400
401 if(ta.form){
402 var resetValue = ta.value;
403 this.reset = function(){
404 var current = this.getValue();
405 if(current !== resetValue){
406 this.replaceValue(resetValue);
407 }
408 };
409 on(ta.form, "submit", lang.hitch(this, function(){
410 // Copy value to the <textarea> so it gets submitted along with form.
411 // FIXME: should we be calling close() here instead?
412 domAttr.set(ta, 'disabled', this.disabled); // don't submit the value if disabled
413 ta.value = this.getValue();
414 }));
415 }
416 }else{
417 html = htmlapi.getChildrenHtml(dn);
418 dn.innerHTML = "";
419 }
420 this.value = html;
421
422 // If we're a list item we have to put in a blank line to force the
423 // bullet to nicely align at the top of text
424 if(dn.nodeName && dn.nodeName === "LI"){
425 dn.innerHTML = " <br>";
426 }
427
428 // Construct the editor div structure.
429 this.header = dn.ownerDocument.createElement("div");
430 dn.appendChild(this.header);
431 this.editingArea = dn.ownerDocument.createElement("div");
432 dn.appendChild(this.editingArea);
433 this.footer = dn.ownerDocument.createElement("div");
434 dn.appendChild(this.footer);
435
436 if(!this.name){
437 this.name = this.id + "_AUTOGEN";
438 }
439
440 // User has pressed back/forward button so we lost the text in the editor, but it's saved
441 // in a hidden <textarea> (which contains the data for all the editors on this page),
442 // so get editor value from there
443 if(this.name !== "" && (!config["useXDomain"] || config["allowXdRichTextSave"])){
444 var saveTextarea = dom.byId(dijit._scopeName + "._editor.RichText.value");
445 if(saveTextarea && saveTextarea.value !== ""){
446 var datas = saveTextarea.value.split(this._SEPARATOR), i = 0, dat;
447 while((dat = datas[i++])){
448 var data = dat.split(this._NAME_CONTENT_SEP);
449 if(data[0] === this.name){
450 this.value = data[1];
451 datas = datas.splice(i, 1);
452 saveTextarea.value = datas.join(this._SEPARATOR);
453 break;
454 }
455 }
456 }
457
458 if(!RichText._globalSaveHandler){
459 RichText._globalSaveHandler = {};
460 unload.addOnUnload(function(){
461 var id;
462 for(id in RichText._globalSaveHandler){
463 var f = RichText._globalSaveHandler[id];
464 if(lang.isFunction(f)){
465 f();
466 }
467 }
468 });
469 }
470 RichText._globalSaveHandler[this.id] = lang.hitch(this, "_saveContent");
471 }
472
473 this.isClosed = false;
474
475 var ifr = (this.editorObject = this.iframe = this.ownerDocument.createElement('iframe'));
476 ifr.id = this.id + "_iframe";
477 ifr.style.border = "none";
478 ifr.style.width = "100%";
479 if(this._layoutMode){
480 // iframe should be 100% height, thus getting it's height from surrounding
481 // <div> (which has the correct height set by Editor)
482 ifr.style.height = "100%";
483 }else{
484 if(has("ie") >= 7){
485 if(this.height){
486 ifr.style.height = this.height;
487 }
488 if(this.minHeight){
489 ifr.style.minHeight = this.minHeight;
490 }
491 }else{
492 ifr.style.height = this.height ? this.height : this.minHeight;
493 }
494 }
495 ifr.frameBorder = 0;
496 ifr._loadFunc = lang.hitch(this, function(w){
497 // This method is called when the editor is first loaded and also if the Editor's
498 // dom node is repositioned. Unfortunately repositioning the Editor tends to
499 // clear the iframe's contents, so we can't just no-op in that case.
500
501 this.window = w;
502 this.document = w.document;
503
504 // instantiate class to access selected text in editor's iframe
505 this.selection = new selectionapi.SelectionManager(w);
506
507 if(has("ie")){
508 this._localizeEditorCommands();
509 }
510
511 // Do final setup and set contents of editor.
512 // Use get("value") rather than html in case _loadFunc() is being called for a second time
513 // because editor's DOMNode was repositioned.
514 this.onLoad(this.get("value"));
515 });
516
517 // Attach iframe to document, and set the initial (blank) content.
518 var src = this._getIframeDocTxt().replace(/\\/g, "\\\\").replace(/'/g, "\\'"),
519 s;
520
521 // IE10 and earlier will throw an "Access is denied" error when attempting to access the parent frame if
522 // document.domain has been set, unless the child frame also has the same document.domain set. In some
523 // cases, we can only set document.domain while the document is being constructed using open/write/close;
524 // attempting to set it later results in a different "This method can't be used in this context" error.
525 // However, in at least IE9-10, sometimes the parent.window check will succeed and the access failure will
526 // only happen later when trying to access frameElement, so there is an additional check and fix there
527 // as well. See #17529
528 if (has("ie") < 11) {
529 s = 'javascript:document.open();try{parent.window;}catch(e){document.domain="' + document.domain + '";}' +
530 'document.write(\'' + src + '\');document.close()';
531 }
532 else {
533 s = "javascript: '" + src + "'";
534 }
535
536 // Attach to document before setting the content, to avoid problem w/iframe running in
537 // wrong security context (IE9 and IE11), see #16633.
538 this.editingArea.appendChild(ifr);
539 ifr.src = s;
540
541 // TODO: this is a guess at the default line-height, kinda works
542 if(dn.nodeName === "LI"){
543 dn.lastChild.style.marginTop = "-1.2em";
544 }
545
546 domClass.add(this.domNode, this.baseClass);
547 },
548
549 //static cache variables shared among all instance of this class
550 _local2NativeFormatNames: {},
551 _native2LocalFormatNames: {},
552
553 _getIframeDocTxt: function(){
554 // summary:
555 // Generates the boilerplate text of the document inside the iframe (ie, `<html><head>...</head><body/></html>`).
556 // Editor content (if not blank) should be added afterwards.
557 // tags:
558 // private
559 var _cs = domStyle.getComputedStyle(this.domNode);
560
561 // Find any associated label element, aria-label, or aria-labelledby and get unescaped text.
562 var title;
563 if(this["aria-label"]){
564 title = this["aria-label"];
565 }else{
566 var labelNode = query('label[for="' + this.id + '"]', this.ownerDocument)[0] ||
567 dom.byId(this["aria-labelledby"], this.ownerDocument);
568 if(labelNode){
569 title = labelNode.textContent || labelNode.innerHTML || "";
570 }
571 }
572
573 // The contents inside of <body>. The real contents are set later via a call to setValue().
574 // In auto-expand mode, need a wrapper div for AlwaysShowToolbar plugin to correctly
575 // expand/contract the editor as the content changes.
576 var html = "<div id='dijitEditorBody' role='textbox' aria-multiline='true' " +
577 (title ? " aria-label='" + string.escape(title) + "'" : "") + "></div>";
578
579 var font = [ _cs.fontWeight, _cs.fontSize, _cs.fontFamily ].join(" ");
580
581 // line height is tricky - applying a units value will mess things up.
582 // if we can't get a non-units value, bail out.
583 var lineHeight = _cs.lineHeight;
584 if(lineHeight.indexOf("px") >= 0){
585 lineHeight = parseFloat(lineHeight) / parseFloat(_cs.fontSize);
586 // console.debug(lineHeight);
587 }else if(lineHeight.indexOf("em") >= 0){
588 lineHeight = parseFloat(lineHeight);
589 }else{
590 // If we can't get a non-units value, just default
591 // it to the CSS spec default of 'normal'. Seems to
592 // work better, esp on IE, than '1.0'
593 lineHeight = "normal";
594 }
595 var userStyle = "";
596 var self = this;
597 this.style.replace(/(^|;)\s*(line-|font-?)[^;]+/ig, function(match){
598 match = match.replace(/^;/ig, "") + ';';
599 var s = match.split(":")[0];
600 if(s){
601 s = lang.trim(s);
602 s = s.toLowerCase();
603 var i;
604 var sC = "";
605 for(i = 0; i < s.length; i++){
606 var c = s.charAt(i);
607 switch(c){
608 case "-":
609 i++;
610 c = s.charAt(i).toUpperCase();
611 default:
612 sC += c;
613 }
614 }
615 domStyle.set(self.domNode, sC, "");
616 }
617 userStyle += match + ';';
618 });
619
620 // Now that we have the title, also set it as the title attribute on the iframe
621 this.iframe.setAttribute("title", title);
622
623 // if this.lang is unset then use default value, to avoid invalid setting of lang=""
624 var language = this.lang || kernel.locale.replace(/-.*/, "");
625
626 return [
627 "<!DOCTYPE html>",
628 "<html lang='" + language + "'" + (this.isLeftToRight() ? "" : " dir='rtl'") + ">\n",
629 "<head>\n",
630 "<meta http-equiv='Content-Type' content='text/html'>\n",
631 title ? "<title>" + string.escape(title) + "</title>" : "",
632 "<style>\n",
633 "\tbody,html {\n",
634 "\t\tbackground:transparent;\n",
635 "\t\tpadding: 1px 0 0 0;\n",
636 "\t\tmargin: -1px 0 0 0;\n", // remove extraneous vertical scrollbar on safari and firefox
637 "\t}\n",
638 "\tbody,html,#dijitEditorBody { outline: none; }",
639
640 // Set <body> to expand to full size of editor, so clicking anywhere will work.
641 // Except in auto-expand mode, in which case the editor expands to the size of <body>.
642 // Also determine how scrollers should be applied. In autoexpand mode (height = "") no scrollers on y at all.
643 // But in fixed height mode we want both x/y scrollers.
644 // Scrollers go on <body> since it's been set to height: 100%.
645 "html { height: 100%; width: 100%; overflow: hidden; }\n", // scroll bar is on #dijitEditorBody, shouldn't be on <html>
646 this.height ? "\tbody,#dijitEditorBody { height: 100%; width: 100%; overflow: auto; }\n" :
647 "\tbody,#dijitEditorBody { min-height: " + this.minHeight + "; width: 100%; overflow-x: auto; overflow-y: hidden; }\n",
648
649 // TODO: left positioning will cause contents to disappear out of view
650 // if it gets too wide for the visible area
651 "\tbody{\n",
652 "\t\ttop:0px;\n",
653 "\t\tleft:0px;\n",
654 "\t\tright:0px;\n",
655 "\t\tfont:", font, ";\n",
656 ((this.height || has("opera")) ? "" : "\t\tposition: fixed;\n"),
657 "\t\tline-height:", lineHeight, ";\n",
658 "\t}\n",
659 "\tp{ margin: 1em 0; }\n",
660
661 "\tli > ul:-moz-first-node, li > ol:-moz-first-node{ padding-top: 1.2em; }\n",
662 // Can't set min-height in IE>=9, it puts layout on li, which puts move/resize handles.
663 // Also can't set it on Edge, as it leads to strange behavior where hitting the return key
664 // doesn't start a new list item.
665 (has("ie") || has("trident") || has("edge") ? "" : "\tli{ min-height:1.2em; }\n"),
666 "</style>\n",
667 this._applyEditingAreaStyleSheets(), "\n",
668 "</head>\n<body role='application'",
669 title ? " aria-label='" + string.escape(title) + "'" : "",
670
671 // Onload handler fills in real editor content.
672 // On IE9, sometimes onload is called twice, and the first time frameElement is null (test_FullScreen.html)
673 // On IE9-10, it is also possible that accessing window.parent in the initial creation of the
674 // iframe DOM will succeed, but trying to access window.frameElement will fail, in which case we
675 // *can* set the domain without a "This method can't be used in this context" error. See #17529
676 "onload='try{frameElement && frameElement._loadFunc(window,document)}catch(e){document.domain=\"" + document.domain + "\";frameElement._loadFunc(window,document)}' ",
677 "style='" + userStyle + "'>", html, "</body>\n</html>"
678 ].join(""); // String
679 },
680
681 _applyEditingAreaStyleSheets: function(){
682 // summary:
683 // apply the specified css files in styleSheets
684 // tags:
685 // private
686 var files = [];
687 if(this.styleSheets){
688 files = this.styleSheets.split(';');
689 this.styleSheets = '';
690 }
691
692 //empty this.editingAreaStyleSheets here, as it will be filled in addStyleSheet
693 files = files.concat(this.editingAreaStyleSheets);
694 this.editingAreaStyleSheets = [];
695
696 var text = '', i = 0, url, ownerWindow = winUtils.get(this.ownerDocument);
697 while((url = files[i++])){
698 var abstring = (new _Url(ownerWindow.location, url)).toString();
699 this.editingAreaStyleSheets.push(abstring);
700 text += '<link rel="stylesheet" type="text/css" href="' + abstring + '"/>';
701 }
702 return text;
703 },
704
705 addStyleSheet: function(/*dojo/_base/url*/ uri){
706 // summary:
707 // add an external stylesheet for the editing area
708 // uri:
709 // Url of the external css file
710 var url = uri.toString(), ownerWindow = winUtils.get(this.ownerDocument);
711
712 //if uri is relative, then convert it to absolute so that it can be resolved correctly in iframe
713 if(url.charAt(0) === '.' || (url.charAt(0) !== '/' && !uri.host)){
714 url = (new _Url(ownerWindow.location, url)).toString();
715 }
716
717 if(array.indexOf(this.editingAreaStyleSheets, url) > -1){
718 // console.debug("dijit/_editor/RichText.addStyleSheet(): Style sheet "+url+" is already applied");
719 return;
720 }
721
722 this.editingAreaStyleSheets.push(url);
723 this.onLoadDeferred.then(lang.hitch(this, function(){
724 if(this.document.createStyleSheet){ //IE
725 this.document.createStyleSheet(url);
726 }else{ //other browser
727 var head = this.document.getElementsByTagName("head")[0];
728 var stylesheet = this.document.createElement("link");
729 stylesheet.rel = "stylesheet";
730 stylesheet.type = "text/css";
731 stylesheet.href = url;
732 head.appendChild(stylesheet);
733 }
734 }));
735 },
736
737 removeStyleSheet: function(/*dojo/_base/url*/ uri){
738 // summary:
739 // remove an external stylesheet for the editing area
740 var url = uri.toString(), ownerWindow = winUtils.get(this.ownerDocument);
741 //if uri is relative, then convert it to absolute so that it can be resolved correctly in iframe
742 if(url.charAt(0) === '.' || (url.charAt(0) !== '/' && !uri.host)){
743 url = (new _Url(ownerWindow.location, url)).toString();
744 }
745 var index = array.indexOf(this.editingAreaStyleSheets, url);
746 if(index === -1){
747 // console.debug("dijit/_editor/RichText.removeStyleSheet(): Style sheet "+url+" has not been applied");
748 return;
749 }
750 delete this.editingAreaStyleSheets[index];
751 query('link[href="' + url + '"]', this.window.document).orphan();
752 },
753
754 // disabled: Boolean
755 // The editor is disabled; the text cannot be changed.
756 disabled: false,
757
758 _mozSettingProps: {'styleWithCSS': false},
759 _setDisabledAttr: function(/*Boolean*/ value){
760 value = !!value;
761 this._set("disabled", value);
762 if(!this.isLoaded){
763 return;
764 } // this method requires init to be complete
765 var preventIEfocus = has("ie") && (this.isLoaded || !this.focusOnLoad);
766 if(preventIEfocus){
767 this.editNode.unselectable = "on";
768 }
769 this.editNode.contentEditable = !value;
770 this.editNode.tabIndex = value ? "-1" : this.tabIndex;
771 if(preventIEfocus){
772 this.defer(function(){
773 if(this.editNode){ // guard in case widget destroyed before timeout
774 this.editNode.unselectable = "off";
775 }
776 });
777 }
778 if(has("mozilla") && !value && this._mozSettingProps){
779 var ps = this._mozSettingProps;
780 var n;
781 for(n in ps){
782 if(ps.hasOwnProperty(n)){
783 try{
784 this.document.execCommand(n, false, ps[n]);
785 }catch(e2){
786 }
787 }
788 }
789 }
790 this._disabledOK = true;
791 },
792
793 /* Event handlers
794 *****************/
795
796 onLoad: function(/*String*/ html){
797 // summary:
798 // Handler after the iframe finishes loading.
799 // html: String
800 // Editor contents should be set to this value
801 // tags:
802 // protected
803
804 if(!this.window.__registeredWindow){
805 this.window.__registeredWindow = true;
806 this._iframeRegHandle = focus.registerIframe(this.iframe);
807 }
808
809 // there's a wrapper div around the content, see _getIframeDocTxt().
810 this.editNode = this.document.body.firstChild;
811 var _this = this;
812
813 // Helper code so IE and FF skip over focusing on the <iframe> and just focus on the inner <div>.
814 // See #4996 IE wants to focus the BODY tag.
815 this.beforeIframeNode = domConstruct.place("<div tabIndex=-1></div>", this.iframe, "before");
816 this.afterIframeNode = domConstruct.place("<div tabIndex=-1></div>", this.iframe, "after");
817 this.iframe.onfocus = this.document.onfocus = function(){
818 _this.editNode.focus();
819 };
820
821 this.focusNode = this.editNode; // for InlineEditBox
822
823
824 var events = this.events.concat(this.captureEvents);
825 var ap = this.iframe ? this.document : this.editNode;
826 this.own.apply(this,
827 array.map(events, function(item){
828 var type = item.toLowerCase().replace(/^on/, "");
829 return on(ap, type, lang.hitch(this, item));
830 }, this)
831 );
832
833 this.own(
834 // mouseup in the margin does not generate an onclick event
835 on(ap, "mouseup", lang.hitch(this, "onClick"))
836 );
837
838 if(has("ie")){ // IE contentEditable
839 this.own(on(this.document, "mousedown", lang.hitch(this, "_onIEMouseDown"))); // #4996 fix focus
840
841 // give the node Layout on IE
842 // TODO: this may no longer be needed, since we've reverted IE to using an iframe,
843 // not contentEditable. Removing it would also probably remove the need for creating
844 // the extra <div> in _getIframeDocTxt()
845 this.editNode.style.zoom = 1.0;
846 }
847
848 if(has("webkit")){
849 //WebKit sometimes doesn't fire right on selections, so the toolbar
850 //doesn't update right. Therefore, help it out a bit with an additional
851 //listener. A mouse up will typically indicate a display change, so fire this
852 //and get the toolbar to adapt. Reference: #9532
853 this._webkitListener = this.own(on(this.document, "mouseup", lang.hitch(this, "onDisplayChanged")))[0];
854 this.own(on(this.document, "mousedown", lang.hitch(this, function(e){
855 var t = e.target;
856 if(t && (t === this.document.body || t === this.document)){
857 // Since WebKit uses the inner DIV, we need to check and set position.
858 // See: #12024 as to why the change was made.
859 this.defer("placeCursorAtEnd");
860 }
861 })));
862 }
863
864 if(has("ie")){
865 // Try to make sure 'hidden' elements aren't visible in edit mode (like browsers other than IE
866 // do). See #9103
867 try{
868 this.document.execCommand('RespectVisibilityInDesign', true, null);
869 }catch(e){/* squelch */
870 }
871 }
872
873 this.isLoaded = true;
874
875 this.set('disabled', this.disabled); // initialize content to editable (or not)
876
877 // Note that setValue() call will only work after isLoaded is set to true (above)
878
879 // Set up a function to allow delaying the setValue until a callback is fired
880 // This ensures extensions like dijit.Editor have a way to hold the value set
881 // until plugins load (and do things like register filters).
882 var setContent = lang.hitch(this, function(){
883 this.setValue(html);
884
885 // Tell app that the Editor has finished loading. isFulfilled() check avoids spurious
886 // console warning when this function is called repeatedly because Editor DOMNode was moved.
887 if(this.onLoadDeferred && !this.onLoadDeferred.isFulfilled()){
888 this.onLoadDeferred.resolve(true);
889 }
890
891 this.onDisplayChanged();
892 if(this.focusOnLoad){
893 // after the document loads, then set focus after updateInterval expires so that
894 // onNormalizedDisplayChanged has run to avoid input caret issues
895 domReady(lang.hitch(this, "defer", "focus", this.updateInterval));
896 }
897 // Save off the initial content now
898 this.value = this.getValue(true);
899 });
900 if(this.setValueDeferred){
901 this.setValueDeferred.then(setContent);
902 }else{
903 setContent();
904 }
905 },
906
907 onKeyDown: function(/* Event */ e){
908 // summary:
909 // Handler for keydown event
910 // tags:
911 // protected
912
913 // Modifier keys should not cause the onKeyPressed event because they do not cause any change to the
914 // display
915 if(e.keyCode === keys.SHIFT ||
916 e.keyCode === keys.ALT ||
917 e.keyCode === keys.META ||
918 e.keyCode === keys.CTRL){
919 return true;
920 }
921
922 if(e.keyCode === keys.TAB && this.isTabIndent){
923 //prevent tab from moving focus out of editor
924 e.stopPropagation();
925 e.preventDefault();
926
927 // FIXME: this is a poor-man's indent/outdent. It would be
928 // better if it added 4 "&nbsp;" chars in an undoable way.
929 // Unfortunately pasteHTML does not prove to be undoable
930 if(this.queryCommandEnabled((e.shiftKey ? "outdent" : "indent"))){
931 this.execCommand((e.shiftKey ? "outdent" : "indent"));
932 }
933 }
934
935 // Make tab and shift-tab skip over the <iframe>, going from the nested <div> to the toolbar
936 // or next element after the editor
937 if(e.keyCode == keys.TAB && !this.isTabIndent && !e.ctrlKey && !e.altKey){
938 if(e.shiftKey){
939 // focus the <iframe> so the browser will shift-tab away from it instead
940 this.beforeIframeNode.focus();
941 }else{
942 // focus node after the <iframe> so the browser will tab away from it instead
943 this.afterIframeNode.focus();
944 }
945
946 // Prevent onKeyPressed from firing in order to avoid triggering a display change event when the
947 // editor is tabbed away; this fixes toolbar controls being inappropriately disabled in IE9+
948 return true;
949 }
950
951 if(has("ie") < 9 && e.keyCode === keys.BACKSPACE && this.document.selection.type === "Control"){
952 // IE has a bug where if a non-text object is selected in the editor,
953 // hitting backspace would act as if the browser's back button was
954 // clicked instead of deleting the object. see #1069
955 e.stopPropagation();
956 e.preventDefault();
957 this.execCommand("delete");
958 }
959
960 if(has("ff")){
961 if(e.keyCode === keys.PAGE_UP || e.keyCode === keys.PAGE_DOWN){
962 if(this.editNode.clientHeight >= this.editNode.scrollHeight){
963 // Stop the event to prevent firefox from trapping the cursor when there is no scroll bar.
964 e.preventDefault();
965 }
966 }
967 }
968
969 var handlers = this._keyHandlers[e.keyCode],
970 args = arguments;
971
972 if(handlers && !e.altKey){
973 array.some(handlers, function(h){
974 // treat meta- same as ctrl-, for benefit of mac users
975 if(!(h.shift ^ e.shiftKey) && !(h.ctrl ^ (e.ctrlKey || e.metaKey))){
976 if(!h.handler.apply(this, args)){
977 e.preventDefault();
978 }
979 return true;
980 }
981 }, this);
982 }
983
984 // function call after the character has been inserted
985 this.defer("onKeyPressed", 1);
986
987 return true;
988 },
989
990 onKeyUp: function(/*===== e =====*/){
991 // summary:
992 // Handler for onkeyup event
993 // tags:
994 // callback
995 },
996
997 setDisabled: function(/*Boolean*/ disabled){
998 // summary:
999 // Deprecated, use set('disabled', ...) instead.
1000 // tags:
1001 // deprecated
1002 kernel.deprecated('dijit.Editor::setDisabled is deprecated', 'use dijit.Editor::attr("disabled",boolean) instead', 2.0);
1003 this.set('disabled', disabled);
1004 },
1005 _setValueAttr: function(/*String*/ value){
1006 // summary:
1007 // Registers that attr("value", foo) should call setValue(foo)
1008 this.setValue(value);
1009 },
1010 _setDisableSpellCheckAttr: function(/*Boolean*/ disabled){
1011 if(this.document){
1012 domAttr.set(this.document.body, "spellcheck", !disabled);
1013 }else{
1014 // try again after the editor is finished loading
1015 this.onLoadDeferred.then(lang.hitch(this, function(){
1016 domAttr.set(this.document.body, "spellcheck", !disabled);
1017 }));
1018 }
1019 this._set("disableSpellCheck", disabled);
1020 },
1021
1022 addKeyHandler: function(/*String|Number*/ key, /*Boolean*/ ctrl, /*Boolean*/ shift, /*Function*/ handler){
1023 // summary:
1024 // Add a handler for a keyboard shortcut
1025 // tags:
1026 // protected
1027
1028 if(typeof key == "string"){
1029 // Something like Ctrl-B. Since using keydown event, we need to convert string to a number.
1030 key = key.toUpperCase().charCodeAt(0);
1031 }
1032
1033 if(!lang.isArray(this._keyHandlers[key])){
1034 this._keyHandlers[key] = [];
1035 }
1036
1037 this._keyHandlers[key].push({
1038 shift: shift || false,
1039 ctrl: ctrl || false,
1040 handler: handler
1041 });
1042 },
1043
1044 onKeyPressed: function(){
1045 // summary:
1046 // Handler for after the user has pressed a key, and the display has been updated.
1047 // (Runs on a timer so that it runs after the display is updated)
1048 // tags:
1049 // private
1050 this.onDisplayChanged(/*e*/); // can't pass in e
1051 },
1052
1053 onClick: function(/*Event*/ e){
1054 // summary:
1055 // Handler for when the user clicks.
1056 // tags:
1057 // private
1058
1059 // console.info('onClick',this._tryDesignModeOn);
1060 this.onDisplayChanged(e);
1061 },
1062
1063 _onIEMouseDown: function(){
1064 // summary:
1065 // IE only to prevent 2 clicks to focus
1066 // tags:
1067 // protected
1068
1069 if(!this.focused && !this.disabled){
1070 this.focus();
1071 }
1072 },
1073
1074 _onBlur: function(e){
1075 // summary:
1076 // Called from focus manager when focus has moved away from this editor
1077 // tags:
1078 // protected
1079
1080 // Workaround IE problem when you blur the browser windows while an editor is focused: IE hangs
1081 // when you focus editor #1, blur the browser window, and then click editor #0. See #16939.
1082 // Note: Edge doesn't seem to have this problem.
1083 if(has("ie") || has("trident")){
1084 this.defer(function(){
1085 if(!focus.curNode){
1086 this.ownerDocumentBody.focus();
1087 }
1088 });
1089 }
1090
1091 this.inherited(arguments);
1092
1093 var newValue = this.getValue(true);
1094 if(newValue !== this.value){
1095 this.onChange(newValue);
1096 }
1097 this._set("value", newValue);
1098 },
1099
1100 _onFocus: function(/*Event*/ e){
1101 // summary:
1102 // Called from focus manager when focus has moved into this editor
1103 // tags:
1104 // protected
1105
1106 // console.info('_onFocus')
1107 if(!this.disabled){
1108 if(!this._disabledOK){
1109 this.set('disabled', false);
1110 }
1111 this.inherited(arguments);
1112 }
1113 },
1114
1115 // TODO: remove in 2.0
1116 blur: function(){
1117 // summary:
1118 // Remove focus from this instance.
1119 // tags:
1120 // deprecated
1121 if(!has("ie") && this.window.document.documentElement && this.window.document.documentElement.focus){
1122 this.window.document.documentElement.focus();
1123 }else if(this.ownerDocumentBody.focus){
1124 this.ownerDocumentBody.focus();
1125 }
1126 },
1127
1128 focus: function(){
1129 // summary:
1130 // Move focus to this editor
1131 if(!this.isLoaded){
1132 this.focusOnLoad = true;
1133 return;
1134 }
1135 if(has("ie") < 9){
1136 //this.editNode.focus(); -> causes IE to scroll always (strict and quirks mode) to the top the Iframe
1137 // if we fire the event manually and let the browser handle the focusing, the latest
1138 // cursor position is focused like in FF
1139 this.iframe.fireEvent('onfocus', document.createEventObject()); // createEventObject/fireEvent only in IE < 11
1140 }else{
1141 // Firefox and chrome
1142 this.editNode.focus();
1143 }
1144 },
1145
1146 // _lastUpdate: 0,
1147 updateInterval: 200,
1148 _updateTimer: null,
1149 onDisplayChanged: function(/*Event*/ /*===== e =====*/){
1150 // summary:
1151 // This event will be fired every time the display context
1152 // changes and the result needs to be reflected in the UI.
1153 // description:
1154 // If you don't want to have update too often,
1155 // onNormalizedDisplayChanged should be used instead
1156 // tags:
1157 // private
1158
1159 // var _t=new Date();
1160 if(this._updateTimer){
1161 this._updateTimer.remove();
1162 }
1163 this._updateTimer = this.defer("onNormalizedDisplayChanged", this.updateInterval);
1164
1165 // Technically this should trigger a call to watch("value", ...) registered handlers,
1166 // but getValue() is too slow to call on every keystroke so we don't.
1167 },
1168 onNormalizedDisplayChanged: function(){
1169 // summary:
1170 // This event is fired every updateInterval ms or more
1171 // description:
1172 // If something needs to happen immediately after a
1173 // user change, please use onDisplayChanged instead.
1174 // tags:
1175 // private
1176 delete this._updateTimer;
1177 },
1178 onChange: function(/*===== newContent =====*/){
1179 // summary:
1180 // This is fired if and only if the editor loses focus and
1181 // the content is changed.
1182 },
1183 _normalizeCommand: function(/*String*/ cmd, /*Anything?*/argument){
1184 // summary:
1185 // Used as the advice function to map our
1186 // normalized set of commands to those supported by the target
1187 // browser.
1188 // tags:
1189 // private
1190
1191 var command = cmd.toLowerCase();
1192 if(command === "formatblock"){
1193 if(has("safari") && argument === undefined){
1194 command = "heading";
1195 }
1196 }else if(command === "hilitecolor" && !has("mozilla")){
1197 command = "backcolor";
1198 }
1199
1200 return command;
1201 },
1202 _implCommand: function(/*String*/ cmd){
1203 // summary:
1204 // Used as the function name where we might
1205 // find an override for advice on support
1206 // for this command by the target browser.
1207 // tags:
1208 // private
1209 return "_" + this._normalizeCommand(cmd) + "EnabledImpl";
1210 },
1211
1212 _qcaCache: {},
1213 queryCommandAvailable: function(/*String*/ command){
1214 // summary:
1215 // Tests whether a command is supported by the host. Clients
1216 // SHOULD check whether a command is supported before attempting
1217 // to use it, behaviour for unsupported commands is undefined.
1218 // command:
1219 // The command to test for
1220 // tags:
1221 // private
1222
1223 // memoizing version. See _queryCommandAvailable for computing version
1224 var ca = this._qcaCache[command];
1225 if(ca !== undefined){
1226 return ca;
1227 }
1228 return (this._qcaCache[command] = this._queryCommandAvailable(command));
1229 },
1230
1231 _queryCommandAvailable: function(/*String*/ command){
1232 // summary:
1233 // See queryCommandAvailable().
1234 // tags:
1235 // private
1236
1237 switch(command.toLowerCase()){
1238 case "bold":
1239 case "italic":
1240 case "underline":
1241 case "subscript":
1242 case "superscript":
1243 case "fontname":
1244 case "fontsize":
1245 case "forecolor":
1246 case "hilitecolor":
1247 case "justifycenter":
1248 case "justifyfull":
1249 case "justifyleft":
1250 case "justifyright":
1251 case "delete":
1252 case "selectall":
1253 case "toggledir":
1254
1255 case "createlink":
1256 case "unlink":
1257 case "removeformat":
1258 case "inserthorizontalrule":
1259 case "insertimage":
1260 case "insertorderedlist":
1261 case "insertunorderedlist":
1262 case "indent":
1263 case "outdent":
1264 case "formatblock":
1265 case "inserthtml":
1266 case "undo":
1267 case "redo":
1268 case "strikethrough":
1269 case "tabindent":
1270
1271 case "cut":
1272 case "copy":
1273 case "paste":
1274 return true;
1275
1276 // Note: This code path is apparently never called. Not sure if it should return true or false
1277 // for Edge.
1278 case "blockdirltr":
1279 case "blockdirrtl":
1280 case "dirltr":
1281 case "dirrtl":
1282 case "inlinedirltr":
1283 case "inlinedirrtl":
1284 return has("ie") || has("trident") || has("edge");
1285
1286 // Note: This code path is apparently never called, not even by the dojox/editor table plugins.
1287 // There's also an _inserttableEnabledImpl() method that's also never called.
1288 // Previously this code returned truthy for IE and mozilla, but false for chrome/safari, so
1289 // leaving it that way just in case.
1290 case "inserttable":
1291 case "insertcell":
1292 case "insertcol":
1293 case "insertrow":
1294 case "deletecells":
1295 case "deletecols":
1296 case "deleterows":
1297 case "mergecells":
1298 case "splitcell":
1299 return !has("webkit");
1300
1301 default:
1302 return false;
1303 }
1304 },
1305
1306 execCommand: function(/*String*/ command, argument){
1307 // summary:
1308 // Executes a command in the Rich Text area
1309 // command:
1310 // The command to execute
1311 // argument:
1312 // An optional argument to the command
1313 // tags:
1314 // protected
1315 var returnValue;
1316
1317 //focus() is required for IE to work
1318 //In addition, focus() makes sure after the execution of
1319 //the command, the editor receives the focus as expected
1320 if(this.focused){
1321 // put focus back in the iframe, unless focus has somehow been shifted out of the editor completely
1322 this.focus();
1323 }
1324
1325 command = this._normalizeCommand(command, argument);
1326
1327 if(argument !== undefined){
1328 if(command === "heading"){
1329 throw new Error("unimplemented");
1330 }else if(command === "formatblock" && (has("ie") || has("trident"))){
1331 // See http://stackoverflow.com/questions/10741831/execcommand-formatblock-headings-in-ie.
1332 // Not necessary on Edge though.
1333 argument = '<' + argument + '>';
1334 }
1335 }
1336
1337 //Check to see if we have any over-rides for commands, they will be functions on this
1338 //widget of the form _commandImpl. If we don't, fall through to the basic native
1339 //exec command of the browser.
1340 var implFunc = "_" + command + "Impl";
1341 if(this[implFunc]){
1342 returnValue = this[implFunc](argument);
1343 }else{
1344 argument = arguments.length > 1 ? argument : null;
1345 if(argument || command !== "createlink"){
1346 returnValue = this.document.execCommand(command, false, argument);
1347 }
1348 }
1349
1350 this.onDisplayChanged();
1351 return returnValue;
1352 },
1353
1354 queryCommandEnabled: function(/*String*/ command){
1355 // summary:
1356 // Check whether a command is enabled or not.
1357 // command:
1358 // The command to execute
1359 // tags:
1360 // protected
1361 if(this.disabled || !this._disabledOK){
1362 return false;
1363 }
1364
1365 command = this._normalizeCommand(command);
1366
1367 //Check to see if we have any over-rides for commands, they will be functions on this
1368 //widget of the form _commandEnabledImpl. If we don't, fall through to the basic native
1369 //command of the browser.
1370 var implFunc = this._implCommand(command);
1371
1372 if(this[implFunc]){
1373 return this[implFunc](command);
1374 }else{
1375 return this._browserQueryCommandEnabled(command);
1376 }
1377 },
1378
1379 queryCommandState: function(command){
1380 // summary:
1381 // Check the state of a given command and returns true or false.
1382 // tags:
1383 // protected
1384
1385 if(this.disabled || !this._disabledOK){
1386 return false;
1387 }
1388 command = this._normalizeCommand(command);
1389 try{
1390 return this.document.queryCommandState(command);
1391 }catch(e){
1392 //Squelch, occurs if editor is hidden on FF 3 (and maybe others.)
1393 return false;
1394 }
1395 },
1396
1397 queryCommandValue: function(command){
1398 // summary:
1399 // Check the value of a given command. This matters most for
1400 // custom selections and complex values like font value setting.
1401 // tags:
1402 // protected
1403
1404 if(this.disabled || !this._disabledOK){
1405 return false;
1406 }
1407 var r;
1408 command = this._normalizeCommand(command);
1409 if(has("ie") && command === "formatblock"){
1410 // This is to deal with IE bug when running in non-English. See _localizeEditorCommands().
1411 // Apparently not needed on IE11 or Edge.
1412 r = this._native2LocalFormatNames[this.document.queryCommandValue(command)];
1413 }else if(has("mozilla") && command === "hilitecolor"){
1414 var oldValue;
1415 try{
1416 oldValue = this.document.queryCommandValue("styleWithCSS");
1417 }catch(e){
1418 oldValue = false;
1419 }
1420 this.document.execCommand("styleWithCSS", false, true);
1421 r = this.document.queryCommandValue(command);
1422 this.document.execCommand("styleWithCSS", false, oldValue);
1423 }else{
1424 r = this.document.queryCommandValue(command);
1425 }
1426 return r;
1427 },
1428
1429 // Misc.
1430
1431 _sCall: function(name, args){
1432 // summary:
1433 // Deprecated, remove for 2.0. New code should access this.selection directly.
1434 // Run the named method of dijit/selection over the
1435 // current editor instance's window, with the passed args.
1436 // tags:
1437 // private deprecated
1438
1439 return this.selection[name].apply(this.selection, args);
1440 },
1441
1442 // FIXME: this is a TON of code duplication. Why?
1443
1444 placeCursorAtStart: function(){
1445 // summary:
1446 // Place the cursor at the start of the editing area.
1447 // tags:
1448 // private
1449
1450 this.focus();
1451
1452 //see comments in placeCursorAtEnd
1453 var isvalid = false;
1454 if(has("mozilla")){
1455 // TODO: Is this branch even necessary?
1456 var first = this.editNode.firstChild;
1457 while(first){
1458 if(first.nodeType === 3){
1459 if(first.nodeValue.replace(/^\s+|\s+$/g, "").length > 0){
1460 isvalid = true;
1461 this.selection.selectElement(first);
1462 break;
1463 }
1464 }else if(first.nodeType === 1){
1465 isvalid = true;
1466 var tg = first.tagName ? first.tagName.toLowerCase() : "";
1467 // Collapse before childless tags.
1468 if(/br|input|img|base|meta|area|basefont|hr|link/.test(tg)){
1469 this.selection.selectElement(first);
1470 }else{
1471 // Collapse inside tags with children.
1472 this.selection.selectElementChildren(first);
1473 }
1474 break;
1475 }
1476 first = first.nextSibling;
1477 }
1478 }else{
1479 isvalid = true;
1480 this.selection.selectElementChildren(this.editNode);
1481 }
1482 if(isvalid){
1483 this.selection.collapse(true);
1484 }
1485 },
1486
1487 placeCursorAtEnd: function(){
1488 // summary:
1489 // Place the cursor at the end of the editing area.
1490 // tags:
1491 // private
1492
1493 this.focus();
1494
1495 //In mozilla, if last child is not a text node, we have to use
1496 // selectElementChildren on this.editNode.lastChild otherwise the
1497 // cursor would be placed at the end of the closing tag of
1498 //this.editNode.lastChild
1499 var isvalid = false;
1500 if(has("mozilla")){
1501 var last = this.editNode.lastChild;
1502 while(last){
1503 if(last.nodeType === 3){
1504 if(last.nodeValue.replace(/^\s+|\s+$/g, "").length > 0){
1505 isvalid = true;
1506 this.selection.selectElement(last);
1507 break;
1508 }
1509 }else if(last.nodeType === 1){
1510 isvalid = true;
1511 this.selection.selectElement(last.lastChild || last);
1512 break;
1513 }
1514 last = last.previousSibling;
1515 }
1516 }else{
1517 isvalid = true;
1518 this.selection.selectElementChildren(this.editNode);
1519 }
1520 if(isvalid){
1521 this.selection.collapse(false);
1522 }
1523 },
1524
1525 getValue: function(/*Boolean?*/ nonDestructive){
1526 // summary:
1527 // Return the current content of the editing area (post filters
1528 // are applied). Users should call get('value') instead.
1529 // nonDestructive:
1530 // defaults to false. Should the post-filtering be run over a copy
1531 // of the live DOM? Most users should pass "true" here unless they
1532 // *really* know that none of the installed filters are going to
1533 // mess up the editing session.
1534 // tags:
1535 // private
1536 if(this.textarea){
1537 if(this.isClosed || !this.isLoaded){
1538 return this.textarea.value;
1539 }
1540 }
1541
1542 return this.isLoaded ? this._postFilterContent(null, nonDestructive) : this.value;
1543 },
1544 _getValueAttr: function(){
1545 // summary:
1546 // Hook to make attr("value") work
1547 return this.getValue(true);
1548 },
1549
1550 setValue: function(/*String*/ html){
1551 // summary:
1552 // This function sets the content. No undo history is preserved.
1553 // Users should use set('value', ...) instead.
1554 // tags:
1555 // deprecated
1556
1557 // TODO: remove this and getValue() for 2.0, and move code to _setValueAttr()
1558
1559 if(!this.isLoaded){
1560 // try again after the editor is finished loading
1561 this.onLoadDeferred.then(lang.hitch(this, function(){
1562 this.setValue(html);
1563 }));
1564 return;
1565 }
1566 if(this.textarea && (this.isClosed || !this.isLoaded)){
1567 this.textarea.value = html;
1568 }else{
1569 html = this._preFilterContent(html);
1570 var node = this.isClosed ? this.domNode : this.editNode;
1571
1572 node.innerHTML = html;
1573 this._preDomFilterContent(node);
1574 }
1575
1576 this.onDisplayChanged();
1577 this._set("value", this.getValue(true));
1578 },
1579
1580 replaceValue: function(/*String*/ html){
1581 // summary:
1582 // This function set the content while trying to maintain the undo stack
1583 // (now only works fine with Moz, this is identical to setValue in all
1584 // other browsers)
1585 // tags:
1586 // protected
1587
1588 if(this.isClosed){
1589 this.setValue(html);
1590 }else if(this.window && this.window.getSelection && !has("mozilla")){ // Safari
1591 // look ma! it's a totally f'd browser!
1592 this.setValue(html);
1593 }else if(this.window && this.window.getSelection){ // Moz
1594 html = this._preFilterContent(html);
1595 this.execCommand("selectall");
1596 this.execCommand("inserthtml", html);
1597 this._preDomFilterContent(this.editNode);
1598 }else if(this.document && this.document.selection){//IE
1599 //In IE, when the first element is not a text node, say
1600 //an <a> tag, when replacing the content of the editing
1601 //area, the <a> tag will be around all the content
1602 //so for now, use setValue for IE too
1603 this.setValue(html);
1604 }
1605
1606 this._set("value", this.getValue(true));
1607 },
1608
1609 _preFilterContent: function(/*String*/ html){
1610 // summary:
1611 // Filter the input before setting the content of the editing
1612 // area. DOM pre-filtering may happen after this
1613 // string-based filtering takes place but as of 1.2, this is not
1614 // guaranteed for operations such as the inserthtml command.
1615 // tags:
1616 // private
1617
1618 var ec = html;
1619 array.forEach(this.contentPreFilters, function(ef){
1620 if(ef){
1621 ec = ef(ec);
1622 }
1623 });
1624 return ec;
1625 },
1626 _preDomFilterContent: function(/*DomNode*/ dom){
1627 // summary:
1628 // filter the input's live DOM. All filter operations should be
1629 // considered to be "live" and operating on the DOM that the user
1630 // will be interacting with in their editing session.
1631 // tags:
1632 // private
1633 dom = dom || this.editNode;
1634 array.forEach(this.contentDomPreFilters, function(ef){
1635 if(ef && lang.isFunction(ef)){
1636 ef(dom);
1637 }
1638 }, this);
1639 },
1640
1641 _postFilterContent: function(/*DomNode|DomNode[]|String?*/ dom, /*Boolean?*/ nonDestructive){
1642 // summary:
1643 // filter the output after getting the content of the editing area
1644 //
1645 // description:
1646 // post-filtering allows plug-ins and users to specify any number
1647 // of transforms over the editor's content, enabling many common
1648 // use-cases such as transforming absolute to relative URLs (and
1649 // vice-versa), ensuring conformance with a particular DTD, etc.
1650 // The filters are registered in the contentDomPostFilters and
1651 // contentPostFilters arrays. Each item in the
1652 // contentDomPostFilters array is a function which takes a DOM
1653 // Node or array of nodes as its only argument and returns the
1654 // same. It is then passed down the chain for further filtering.
1655 // The contentPostFilters array behaves the same way, except each
1656 // member operates on strings. Together, the DOM and string-based
1657 // filtering allow the full range of post-processing that should
1658 // be necessaray to enable even the most agressive of post-editing
1659 // conversions to take place.
1660 //
1661 // If nonDestructive is set to "true", the nodes are cloned before
1662 // filtering proceeds to avoid potentially destructive transforms
1663 // to the content which may still needed to be edited further.
1664 // Once DOM filtering has taken place, the serialized version of
1665 // the DOM which is passed is run through each of the
1666 // contentPostFilters functions.
1667 //
1668 // dom:
1669 // a node, set of nodes, which to filter using each of the current
1670 // members of the contentDomPostFilters and contentPostFilters arrays.
1671 //
1672 // nonDestructive:
1673 // defaults to "false". If true, ensures that filtering happens on
1674 // a clone of the passed-in content and not the actual node
1675 // itself.
1676 //
1677 // tags:
1678 // private
1679
1680 var ec;
1681 if(!lang.isString(dom)){
1682 dom = dom || this.editNode;
1683 if(this.contentDomPostFilters.length){
1684 if(nonDestructive){
1685 dom = lang.clone(dom);
1686 }
1687 array.forEach(this.contentDomPostFilters, function(ef){
1688 dom = ef(dom);
1689 });
1690 }
1691 ec = htmlapi.getChildrenHtml(dom);
1692 }else{
1693 ec = dom;
1694 }
1695
1696 if(!lang.trim(ec.replace(/^\xA0\xA0*/, '').replace(/\xA0\xA0*$/, '')).length){
1697 ec = "";
1698 }
1699
1700 array.forEach(this.contentPostFilters, function(ef){
1701 ec = ef(ec);
1702 });
1703
1704 return ec;
1705 },
1706
1707 _saveContent: function(){
1708 // summary:
1709 // Saves the content in an onunload event if the editor has not been closed
1710 // tags:
1711 // private
1712
1713 var saveTextarea = dom.byId(dijit._scopeName + "._editor.RichText.value");
1714 if(saveTextarea){
1715 if(saveTextarea.value){
1716 saveTextarea.value += this._SEPARATOR;
1717 }
1718 saveTextarea.value += this.name + this._NAME_CONTENT_SEP + this.getValue(true);
1719 }
1720 },
1721
1722
1723 escapeXml: function(/*String*/ str, /*Boolean*/ noSingleQuotes){
1724 // summary:
1725 // Adds escape sequences for special characters in XML.
1726 // Optionally skips escapes for single quotes
1727 // tags:
1728 // private
1729
1730 str = str.replace(/&/gm, "&amp;").replace(/</gm, "&lt;").replace(/>/gm, "&gt;").replace(/"/gm, "&quot;");
1731 if(!noSingleQuotes){
1732 str = str.replace(/'/gm, "&#39;");
1733 }
1734 return str; // string
1735 },
1736
1737 getNodeHtml: function(/* DomNode */ node){
1738 // summary:
1739 // Deprecated. Use dijit/_editor/html::_getNodeHtml() instead.
1740 // tags:
1741 // deprecated
1742 kernel.deprecated('dijit.Editor::getNodeHtml is deprecated', 'use dijit/_editor/html::getNodeHtml instead', 2);
1743 return htmlapi.getNodeHtml(node); // String
1744 },
1745
1746 getNodeChildrenHtml: function(/* DomNode */ dom){
1747 // summary:
1748 // Deprecated. Use dijit/_editor/html::getChildrenHtml() instead.
1749 // tags:
1750 // deprecated
1751 kernel.deprecated('dijit.Editor::getNodeChildrenHtml is deprecated', 'use dijit/_editor/html::getChildrenHtml instead', 2);
1752 return htmlapi.getChildrenHtml(dom);
1753 },
1754
1755 close: function(/*Boolean?*/ save){
1756 // summary:
1757 // Kills the editor and optionally writes back the modified contents to the
1758 // element from which it originated.
1759 // save:
1760 // Whether or not to save the changes. If false, the changes are discarded.
1761 // tags:
1762 // private
1763
1764 if(this.isClosed){
1765 return;
1766 }
1767
1768 if(!arguments.length){
1769 save = true;
1770 }
1771 if(save){
1772 this._set("value", this.getValue(true));
1773 }
1774
1775 // line height is squashed for iframes
1776 // FIXME: why was this here? if(this.iframe){ this.domNode.style.lineHeight = null; }
1777
1778 if(this.interval){
1779 clearInterval(this.interval);
1780 }
1781
1782 if(this._webkitListener){
1783 // Cleanup of WebKit fix: #9532
1784 this._webkitListener.remove();
1785 delete this._webkitListener;
1786 }
1787
1788 // Guard against memory leaks on IE (see #9268)
1789 if(has("ie")){
1790 this.iframe.onfocus = null;
1791 }
1792 this.iframe._loadFunc = null;
1793
1794 if(this._iframeRegHandle){
1795 this._iframeRegHandle.remove();
1796 delete this._iframeRegHandle;
1797 }
1798
1799 if(this.textarea){
1800 var s = this.textarea.style;
1801 s.position = "";
1802 s.left = s.top = "";
1803 if(has("ie")){
1804 s.overflow = this.__overflow;
1805 this.__overflow = null;
1806 }
1807 this.textarea.value = this.value;
1808 domConstruct.destroy(this.domNode);
1809 this.domNode = this.textarea;
1810 }else{
1811 // Note that this destroys the iframe
1812 this.domNode.innerHTML = this.value;
1813 }
1814 delete this.iframe;
1815
1816 domClass.remove(this.domNode, this.baseClass);
1817 this.isClosed = true;
1818 this.isLoaded = false;
1819
1820 delete this.editNode;
1821 delete this.focusNode;
1822
1823 if(this.window && this.window._frameElement){
1824 this.window._frameElement = null;
1825 }
1826
1827 this.window = null;
1828 this.document = null;
1829 this.editingArea = null;
1830 this.editorObject = null;
1831 },
1832
1833 destroy: function(){
1834 if(!this.isClosed){
1835 this.close(false);
1836 }
1837 if(this._updateTimer){
1838 this._updateTimer.remove();
1839 }
1840 this.inherited(arguments);
1841 if(RichText._globalSaveHandler){
1842 delete RichText._globalSaveHandler[this.id];
1843 }
1844 },
1845
1846 _removeMozBogus: function(/* String */ html){
1847 // summary:
1848 // Post filter to remove unwanted HTML attributes generated by mozilla
1849 // tags:
1850 // private
1851 return html.replace(/\stype="_moz"/gi, '').replace(/\s_moz_dirty=""/gi, '').replace(/_moz_resizing="(true|false)"/gi, ''); // String
1852 },
1853 _removeWebkitBogus: function(/* String */ html){
1854 // summary:
1855 // Post filter to remove unwanted HTML attributes generated by webkit
1856 // tags:
1857 // private
1858 html = html.replace(/\sclass="webkit-block-placeholder"/gi, '');
1859 html = html.replace(/\sclass="apple-style-span"/gi, '');
1860 // For some reason copy/paste sometime adds extra meta tags for charset on
1861 // webkit (chrome) on mac.They need to be removed. See: #12007"
1862 html = html.replace(/<meta charset=\"utf-8\" \/>/gi, '');
1863 return html; // String
1864 },
1865 _normalizeFontStyle: function(/* String */ html){
1866 // summary:
1867 // Convert 'strong' and 'em' to 'b' and 'i'.
1868 // description:
1869 // Moz can not handle strong/em tags correctly, so to help
1870 // mozilla and also to normalize output, convert them to 'b' and 'i'.
1871 //
1872 // Note the IE generates 'strong' and 'em' rather than 'b' and 'i'
1873 // tags:
1874 // private
1875 return html.replace(/<(\/)?strong([ \>])/gi, '<$1b$2')
1876 .replace(/<(\/)?em([ \>])/gi, '<$1i$2'); // String
1877 },
1878
1879 _preFixUrlAttributes: function(/* String */ html){
1880 // summary:
1881 // Pre-filter to do fixing to href attributes on `<a>` and `<img>` tags
1882 // tags:
1883 // private
1884 return html.replace(/(?:(<a(?=\s).*?\shref=)("|')(.*?)\2)|(?:(<a\s.*?href=)([^"'][^ >]+))/gi,
1885 '$1$4$2$3$5$2 _djrealurl=$2$3$5$2')
1886 .replace(/(?:(<img(?=\s).*?\ssrc=)("|')(.*?)\2)|(?:(<img\s.*?src=)([^"'][^ >]+))/gi,
1887 '$1$4$2$3$5$2 _djrealurl=$2$3$5$2'); // String
1888 },
1889
1890 /*****************************************************************************
1891 The following functions implement HTML manipulation commands for various
1892 browser/contentEditable implementations. The goal of them is to enforce
1893 standard behaviors of them.
1894 ******************************************************************************/
1895
1896 /*** queryCommandEnabled implementations ***/
1897
1898 _browserQueryCommandEnabled: function(command){
1899 // summary:
1900 // Implementation to call to the native queryCommandEnabled of the browser.
1901 // command:
1902 // The command to check.
1903 // tags:
1904 // protected
1905 if(!command){
1906 return false;
1907 }
1908 var elem = has("ie") < 9 ? this.document.selection.createRange() : this.document;
1909 try{
1910 return elem.queryCommandEnabled(command);
1911 }catch(e){
1912 return false;
1913 }
1914 },
1915
1916 _createlinkEnabledImpl: function(/*===== argument =====*/){
1917 // summary:
1918 // This function implements the test for if the create link
1919 // command should be enabled or not.
1920 // argument:
1921 // arguments to the exec command, if any.
1922 // tags:
1923 // protected
1924 var enabled = true;
1925 if(has("opera")){
1926 var sel = this.window.getSelection();
1927 if(sel.isCollapsed){
1928 enabled = true;
1929 }else{
1930 enabled = this.document.queryCommandEnabled("createlink");
1931 }
1932 }else{
1933 enabled = this._browserQueryCommandEnabled("createlink");
1934 }
1935 return enabled;
1936 },
1937
1938 _unlinkEnabledImpl: function(/*===== argument =====*/){
1939 // summary:
1940 // This function implements the test for if the unlink
1941 // command should be enabled or not.
1942 // argument:
1943 // arguments to the exec command, if any.
1944 // tags:
1945 // protected
1946 var enabled = true;
1947 if(has("mozilla") || has("webkit")){
1948 enabled = this.selection.hasAncestorElement("a");
1949 }else{
1950 enabled = this._browserQueryCommandEnabled("unlink");
1951 }
1952 return enabled;
1953 },
1954
1955 _inserttableEnabledImpl: function(/*===== argument =====*/){
1956 // summary:
1957 // This function implements the test for if the inserttable
1958 // command should be enabled or not.
1959 // argument:
1960 // arguments to the exec command, if any.
1961 // tags:
1962 // protected
1963 var enabled = true;
1964 if(has("mozilla") || has("webkit")){
1965 enabled = true;
1966 }else{
1967 enabled = this._browserQueryCommandEnabled("inserttable");
1968 }
1969 return enabled;
1970 },
1971
1972 _cutEnabledImpl: function(/*===== argument =====*/){
1973 // summary:
1974 // This function implements the test for if the cut
1975 // command should be enabled or not.
1976 // argument:
1977 // arguments to the exec command, if any.
1978 // tags:
1979 // protected
1980 var enabled = true;
1981 if(has("webkit")){
1982 // WebKit deems clipboard activity as a security threat and natively would return false
1983 var sel = this.window.getSelection();
1984 if(sel){
1985 sel = sel.toString();
1986 }
1987 enabled = !!sel;
1988 }else{
1989 enabled = this._browserQueryCommandEnabled("cut");
1990 }
1991 return enabled;
1992 },
1993
1994 _copyEnabledImpl: function(/*===== argument =====*/){
1995 // summary:
1996 // This function implements the test for if the copy
1997 // command should be enabled or not.
1998 // argument:
1999 // arguments to the exec command, if any.
2000 // tags:
2001 // protected
2002 var enabled = true;
2003 if(has("webkit")){
2004 // WebKit deems clipboard activity as a security threat and natively would return false
2005 var sel = this.window.getSelection();
2006 if(sel){
2007 sel = sel.toString();
2008 }
2009 enabled = !!sel;
2010 }else{
2011 enabled = this._browserQueryCommandEnabled("copy");
2012 }
2013 return enabled;
2014 },
2015
2016 _pasteEnabledImpl: function(/*===== argument =====*/){
2017 // summary:c
2018 // This function implements the test for if the paste
2019 // command should be enabled or not.
2020 // argument:
2021 // arguments to the exec command, if any.
2022 // tags:
2023 // protected
2024 var enabled = true;
2025 if(has("webkit")){
2026 return true;
2027 }else{
2028 enabled = this._browserQueryCommandEnabled("paste");
2029 }
2030 return enabled;
2031 },
2032
2033 /*** execCommand implementations ***/
2034
2035 _inserthorizontalruleImpl: function(argument){
2036 // summary:
2037 // This function implements the insertion of HTML 'HR' tags.
2038 // into a point on the page. IE doesn't to it right, so
2039 // we have to use an alternate form
2040 // argument:
2041 // arguments to the exec command, if any.
2042 // tags:
2043 // protected
2044 if(has("ie")){
2045 return this._inserthtmlImpl("<hr>");
2046 }
2047 return this.document.execCommand("inserthorizontalrule", false, argument);
2048 },
2049
2050 _unlinkImpl: function(argument){
2051 // summary:
2052 // This function implements the unlink of an 'a' tag.
2053 // argument:
2054 // arguments to the exec command, if any.
2055 // tags:
2056 // protected
2057 if((this.queryCommandEnabled("unlink")) && (has("mozilla") || has("webkit"))){
2058 var a = this.selection.getAncestorElement("a");
2059 this.selection.selectElement(a);
2060 return this.document.execCommand("unlink", false, null);
2061 }
2062 return this.document.execCommand("unlink", false, argument);
2063 },
2064
2065 _hilitecolorImpl: function(argument){
2066 // summary:
2067 // This function implements the hilitecolor command
2068 // argument:
2069 // arguments to the exec command, if any.
2070 // tags:
2071 // protected
2072 var returnValue;
2073 var isApplied = this._handleTextColorOrProperties("hilitecolor", argument);
2074 if(!isApplied){
2075 if(has("mozilla")){
2076 // mozilla doesn't support hilitecolor properly when useCSS is
2077 // set to false (bugzilla #279330)
2078 this.document.execCommand("styleWithCSS", false, true);
2079 console.log("Executing color command.");
2080 returnValue = this.document.execCommand("hilitecolor", false, argument);
2081 this.document.execCommand("styleWithCSS", false, false);
2082 }else{
2083 returnValue = this.document.execCommand("hilitecolor", false, argument);
2084 }
2085 }
2086 return returnValue;
2087 },
2088
2089 _backcolorImpl: function(argument){
2090 // summary:
2091 // This function implements the backcolor command
2092 // argument:
2093 // arguments to the exec command, if any.
2094 // tags:
2095 // protected
2096 if(has("ie")){
2097 // Tested under IE 6 XP2, no problem here, comment out
2098 // IE weirdly collapses ranges when we exec these commands, so prevent it
2099 // var tr = this.document.selection.createRange();
2100 argument = argument ? argument : null;
2101 }
2102 var isApplied = this._handleTextColorOrProperties("backcolor", argument);
2103 if(!isApplied){
2104 isApplied = this.document.execCommand("backcolor", false, argument);
2105 }
2106 return isApplied;
2107 },
2108
2109 _forecolorImpl: function(argument){
2110 // summary:
2111 // This function implements the forecolor command
2112 // argument:
2113 // arguments to the exec command, if any.
2114 // tags:
2115 // protected
2116 if(has("ie")){
2117 // Tested under IE 6 XP2, no problem here, comment out
2118 // IE weirdly collapses ranges when we exec these commands, so prevent it
2119 // var tr = this.document.selection.createRange();
2120 argument = argument ? argument : null;
2121 }
2122 var isApplied = false;
2123 isApplied = this._handleTextColorOrProperties("forecolor", argument);
2124 if(!isApplied){
2125 isApplied = this.document.execCommand("forecolor", false, argument);
2126 }
2127 return isApplied;
2128 },
2129
2130 _inserthtmlImpl: function(argument){
2131 // summary:
2132 // This function implements the insertion of HTML content into
2133 // a point on the page.
2134 // argument:
2135 // The content to insert, if any.
2136 // tags:
2137 // protected
2138 argument = this._preFilterContent(argument);
2139 var rv = true;
2140 if(has("ie") < 9){
2141 var insertRange = this.document.selection.createRange();
2142 if(this.document.selection.type.toUpperCase() === 'CONTROL'){
2143 var n = insertRange.item(0);
2144 while(insertRange.length){
2145 insertRange.remove(insertRange.item(0));
2146 }
2147 n.outerHTML = argument;
2148 }else{
2149 insertRange.pasteHTML(argument);
2150 }
2151 insertRange.select();
2152 }else if(has("trident") < 8){
2153 var insertRange;
2154 var selection = rangeapi.getSelection(this.window);
2155 if(selection && selection.rangeCount && selection.getRangeAt){
2156 insertRange = selection.getRangeAt(0);
2157 insertRange.deleteContents();
2158
2159 var div = domConstruct.create('div');
2160 div.innerHTML = argument;
2161 var node, lastNode;
2162 var n = this.document.createDocumentFragment();
2163 while((node = div.firstChild)){
2164 lastNode = n.appendChild(node);
2165 }
2166 insertRange.insertNode(n);
2167 if(lastNode) {
2168 insertRange = insertRange.cloneRange();
2169 insertRange.setStartAfter(lastNode);
2170 insertRange.collapse(false);
2171 selection.removeAllRanges();
2172 selection.addRange(insertRange);
2173 }
2174 }
2175 }else if(has("mozilla") && !argument.length){
2176 //mozilla can not inserthtml an empty html to delete current selection
2177 //so we delete the selection instead in this case
2178 this.selection.remove(); // FIXME
2179 }else{
2180 rv = this.document.execCommand("inserthtml", false, argument);
2181 }
2182 return rv;
2183 },
2184
2185 _boldImpl: function(argument){
2186 // summary:
2187 // This function implements an over-ride of the bold command.
2188 // argument:
2189 // Not used, operates by selection.
2190 // tags:
2191 // protected
2192 var applied = false;
2193 if(has("ie") || has("trident")){
2194 this._adaptIESelection();
2195 applied = this._adaptIEFormatAreaAndExec("bold");
2196 }
2197 if(!applied){
2198 applied = this.document.execCommand("bold", false, argument);
2199 }
2200 return applied;
2201 },
2202
2203 _italicImpl: function(argument){
2204 // summary:
2205 // This function implements an over-ride of the italic command.
2206 // argument:
2207 // Not used, operates by selection.
2208 // tags:
2209 // protected
2210 var applied = false;
2211 if(has("ie") || has("trident")){
2212 this._adaptIESelection();
2213 applied = this._adaptIEFormatAreaAndExec("italic");
2214 }
2215 if(!applied){
2216 applied = this.document.execCommand("italic", false, argument);
2217 }
2218 return applied;
2219 },
2220
2221 _underlineImpl: function(argument){
2222 // summary:
2223 // This function implements an over-ride of the underline command.
2224 // argument:
2225 // Not used, operates by selection.
2226 // tags:
2227 // protected
2228 var applied = false;
2229 if(has("ie") || has("trident")){
2230 this._adaptIESelection();
2231 applied = this._adaptIEFormatAreaAndExec("underline");
2232 }
2233 if(!applied){
2234 applied = this.document.execCommand("underline", false, argument);
2235 }
2236 return applied;
2237 },
2238
2239 _strikethroughImpl: function(argument){
2240 // summary:
2241 // This function implements an over-ride of the strikethrough command.
2242 // argument:
2243 // Not used, operates by selection.
2244 // tags:
2245 // protected
2246 var applied = false;
2247 if(has("ie") || has("trident")){
2248 this._adaptIESelection();
2249 applied = this._adaptIEFormatAreaAndExec("strikethrough");
2250 }
2251 if(!applied){
2252 applied = this.document.execCommand("strikethrough", false, argument);
2253 }
2254 return applied;
2255 },
2256
2257 _superscriptImpl: function(argument){
2258 // summary:
2259 // This function implements an over-ride of the superscript command.
2260 // argument:
2261 // Not used, operates by selection.
2262 // tags:
2263 // protected
2264 var applied = false;
2265 if(has("ie") || has("trident")){
2266 this._adaptIESelection();
2267 applied = this._adaptIEFormatAreaAndExec("superscript");
2268 }
2269 if(!applied){
2270 applied = this.document.execCommand("superscript", false, argument);
2271 }
2272 return applied;
2273 },
2274
2275 _subscriptImpl: function(argument){
2276 // summary:
2277 // This function implements an over-ride of the superscript command.
2278 // argument:
2279 // Not used, operates by selection.
2280 // tags:
2281 // protected
2282 var applied = false;
2283 if(has("ie") || has("trident")){
2284 this._adaptIESelection();
2285 applied = this._adaptIEFormatAreaAndExec("subscript");
2286
2287 }
2288 if(!applied){
2289 applied = this.document.execCommand("subscript", false, argument);
2290 }
2291 return applied;
2292 },
2293
2294 _fontnameImpl: function(argument){
2295 // summary:
2296 // This function implements the fontname command
2297 // argument:
2298 // arguments to the exec command, if any.
2299 // tags:
2300 // protected
2301 var isApplied;
2302 if(has("ie") || has("trident")){
2303 isApplied = this._handleTextColorOrProperties("fontname", argument);
2304 }
2305 if(!isApplied){
2306 isApplied = this.document.execCommand("fontname", false, argument);
2307 }
2308 return isApplied;
2309 },
2310
2311 _fontsizeImpl: function(argument){
2312 // summary:
2313 // This function implements the fontsize command
2314 // argument:
2315 // arguments to the exec command, if any.
2316 // tags:
2317 // protected
2318 var isApplied;
2319 if(has("ie") || has("trident")){
2320 isApplied = this._handleTextColorOrProperties("fontsize", argument);
2321 }
2322 if(!isApplied){
2323 isApplied = this.document.execCommand("fontsize", false, argument);
2324 }
2325 return isApplied;
2326 },
2327
2328 _insertorderedlistImpl: function(argument){
2329 // summary:
2330 // This function implements the insertorderedlist command
2331 // argument:
2332 // arguments to the exec command, if any.
2333 // tags:
2334 // protected
2335 var applied = false;
2336 if(has("ie") || has("trident") || has("edge")){
2337 applied = this._adaptIEList("insertorderedlist", argument);
2338 }
2339 if(!applied){
2340 applied = this.document.execCommand("insertorderedlist", false, argument);
2341 }
2342 return applied;
2343 },
2344
2345 _insertunorderedlistImpl: function(argument){
2346 // summary:
2347 // This function implements the insertunorderedlist command
2348 // argument:
2349 // arguments to the exec command, if any.
2350 // tags:
2351 // protected
2352 var applied = false;
2353 if(has("ie") || has("trident") || has("edge")){
2354 applied = this._adaptIEList("insertunorderedlist", argument);
2355 }
2356 if(!applied){
2357 applied = this.document.execCommand("insertunorderedlist", false, argument);
2358 }
2359 return applied;
2360 },
2361
2362 getHeaderHeight: function(){
2363 // summary:
2364 // A function for obtaining the height of the header node
2365 return this._getNodeChildrenHeight(this.header); // Number
2366 },
2367
2368 getFooterHeight: function(){
2369 // summary:
2370 // A function for obtaining the height of the footer node
2371 return this._getNodeChildrenHeight(this.footer); // Number
2372 },
2373
2374 _getNodeChildrenHeight: function(node){
2375 // summary:
2376 // An internal function for computing the cumulative height of all child nodes of 'node'
2377 // node:
2378 // The node to process the children of;
2379 var h = 0;
2380 if(node && node.childNodes){
2381 // IE didn't compute it right when position was obtained on the node directly is some cases,
2382 // so we have to walk over all the children manually.
2383 var i;
2384 for(i = 0; i < node.childNodes.length; i++){
2385 var size = domGeometry.position(node.childNodes[i]);
2386 h += size.h;
2387 }
2388 }
2389 return h; // Number
2390 },
2391
2392 _isNodeEmpty: function(node, startOffset){
2393 // summary:
2394 // Function to test if a node is devoid of real content.
2395 // node:
2396 // The node to check.
2397 // tags:
2398 // private.
2399 if(node.nodeType === 1/*element*/){
2400 if(node.childNodes.length > 0){
2401 return this._isNodeEmpty(node.childNodes[0], startOffset); // huh? why test just first child?
2402 }
2403 return true;
2404 }else if(node.nodeType === 3/*text*/){
2405 return (node.nodeValue.substring(startOffset) === "");
2406 }
2407 return false;
2408 },
2409
2410 _removeStartingRangeFromRange: function(node, range){
2411 // summary:
2412 // Function to adjust selection range by removing the current
2413 // start node.
2414 // node:
2415 // The node to remove from the starting range.
2416 // range:
2417 // The range to adapt.
2418 // tags:
2419 // private
2420 if(node.nextSibling){
2421 range.setStart(node.nextSibling, 0);
2422 }else{
2423 var parent = node.parentNode;
2424 while(parent && parent.nextSibling == null){
2425 //move up the tree until we find a parent that has another node, that node will be the next node
2426 parent = parent.parentNode;
2427 }
2428 if(parent){
2429 range.setStart(parent.nextSibling, 0);
2430 }
2431 }
2432 return range;
2433 },
2434
2435 _adaptIESelection: function(){
2436 // summary:
2437 // Function to adapt the IE range by removing leading 'newlines'
2438 // Needed to fix issue with bold/italics/underline not working if
2439 // range included leading 'newlines'.
2440 // In IE, if a user starts a selection at the very end of a line,
2441 // then the native browser commands will fail to execute correctly.
2442 // To work around the issue, we can remove all empty nodes from
2443 // the start of the range selection.
2444 //
2445 // Note: not needed on Edge because Windows 10 won't let the user make
2446 // a selection containing leading or trailing newlines.
2447 var selection = rangeapi.getSelection(this.window);
2448 if(selection && selection.rangeCount && !selection.isCollapsed){
2449 var range = selection.getRangeAt(0);
2450 var firstNode = range.startContainer;
2451 var startOffset = range.startOffset;
2452
2453 while(firstNode.nodeType === 3/*text*/ && startOffset >= firstNode.length && firstNode.nextSibling){
2454 //traverse the text nodes until we get to the one that is actually highlighted
2455 startOffset = startOffset - firstNode.length;
2456 firstNode = firstNode.nextSibling;
2457 }
2458
2459 //Remove the starting ranges until the range does not start with an empty node.
2460 var lastNode = null;
2461 while(this._isNodeEmpty(firstNode, startOffset) && firstNode !== lastNode){
2462 lastNode = firstNode; //this will break the loop in case we can't find the next sibling
2463 range = this._removeStartingRangeFromRange(firstNode, range); //move the start container to the next node in the range
2464 firstNode = range.startContainer;
2465 startOffset = 0; //start at the beginning of the new starting range
2466 }
2467 selection.removeAllRanges();// this will work as long as users cannot select multiple ranges. I have not been able to do that in the editor.
2468 selection.addRange(range);
2469 }
2470 },
2471
2472 _adaptIEFormatAreaAndExec: function(command){
2473 // summary:
2474 // Function to handle IE's quirkiness regarding how it handles
2475 // format commands on a word. This involves a lit of node splitting
2476 // and format cloning.
2477 // command:
2478 // The format command, needed to check if the desired
2479 // command is true or not.
2480 var selection = rangeapi.getSelection(this.window);
2481 var doc = this.document;
2482 var rs, ret, range, txt, startNode, endNode, breaker, sNode;
2483 if(command && selection && selection.isCollapsed){
2484 var isApplied = this.queryCommandValue(command);
2485 if(isApplied){
2486
2487 // We have to split backwards until we hit the format
2488 var nNames = this._tagNamesForCommand(command);
2489 range = selection.getRangeAt(0);
2490 var fs = range.startContainer;
2491 if(fs.nodeType === 3){
2492 var offset = range.endOffset;
2493 if(fs.length < offset){
2494 //We are not looking from the right node, try to locate the correct one
2495 ret = this._adjustNodeAndOffset(rs, offset);
2496 fs = ret.node;
2497 offset = ret.offset;
2498 }
2499 }
2500 var topNode;
2501 while(fs && fs !== this.editNode){
2502 // We have to walk back and see if this is still a format or not.
2503 // Hm, how do I do this?
2504 var tName = fs.tagName ? fs.tagName.toLowerCase() : "";
2505 if(array.indexOf(nNames, tName) > -1){
2506 topNode = fs;
2507 break;
2508 }
2509 fs = fs.parentNode;
2510 }
2511
2512 // Okay, we have a stopping place, time to split things apart.
2513 if(topNode){
2514 // Okay, we know how far we have to split backwards, so we have to split now.
2515 rs = range.startContainer;
2516 var newblock = doc.createElement(topNode.tagName);
2517 domConstruct.place(newblock, topNode, "after");
2518 if(rs && rs.nodeType === 3){
2519 // Text node, we have to split it.
2520 var nodeToMove, tNode;
2521 var endOffset = range.endOffset;
2522 if(rs.length < endOffset){
2523 //We are not splitting the right node, try to locate the correct one
2524 ret = this._adjustNodeAndOffset(rs, endOffset);
2525 rs = ret.node;
2526 endOffset = ret.offset;
2527 }
2528
2529 txt = rs.nodeValue;
2530 startNode = doc.createTextNode(txt.substring(0, endOffset));
2531 var endText = txt.substring(endOffset, txt.length);
2532 if(endText){
2533 endNode = doc.createTextNode(endText);
2534 }
2535 // Place the split, then remove original nodes.
2536 domConstruct.place(startNode, rs, "before");
2537 if(endNode){
2538 breaker = doc.createElement("span");
2539 breaker.className = "ieFormatBreakerSpan";
2540 domConstruct.place(breaker, rs, "after");
2541 domConstruct.place(endNode, breaker, "after");
2542 endNode = breaker;
2543 }
2544 domConstruct.destroy(rs);
2545
2546 // Okay, we split the text. Now we need to see if we're
2547 // parented to the block element we're splitting and if
2548 // not, we have to split all the way up. Ugh.
2549 var parentC = startNode.parentNode;
2550 var tagList = [];
2551 var tagData;
2552 while(parentC !== topNode){
2553 var tg = parentC.tagName;
2554 tagData = {tagName: tg};
2555 tagList.push(tagData);
2556
2557 var newTg = doc.createElement(tg);
2558 // Clone over any 'style' data.
2559 if(parentC.style){
2560 if(newTg.style){
2561 if(parentC.style.cssText){
2562 newTg.style.cssText = parentC.style.cssText;
2563 tagData.cssText = parentC.style.cssText;
2564 }
2565 }
2566 }
2567 // If font also need to clone over any font data.
2568 if(parentC.tagName === "FONT"){
2569 if(parentC.color){
2570 newTg.color = parentC.color;
2571 tagData.color = parentC.color;
2572 }
2573 if(parentC.face){
2574 newTg.face = parentC.face;
2575 tagData.face = parentC.face;
2576 }
2577 if(parentC.size){ // this check was necessary on IE
2578 newTg.size = parentC.size;
2579 tagData.size = parentC.size;
2580 }
2581 }
2582 if(parentC.className){
2583 newTg.className = parentC.className;
2584 tagData.className = parentC.className;
2585 }
2586
2587 // Now move end node and every sibling
2588 // after it over into the new tag.
2589 if(endNode){
2590 nodeToMove = endNode;
2591 while(nodeToMove){
2592 tNode = nodeToMove.nextSibling;
2593 newTg.appendChild(nodeToMove);
2594 nodeToMove = tNode;
2595 }
2596 }
2597 if(newTg.tagName == parentC.tagName){
2598 breaker = doc.createElement("span");
2599 breaker.className = "ieFormatBreakerSpan";
2600 domConstruct.place(breaker, parentC, "after");
2601 domConstruct.place(newTg, breaker, "after");
2602 }else{
2603 domConstruct.place(newTg, parentC, "after");
2604 }
2605 startNode = parentC;
2606 endNode = newTg;
2607 parentC = parentC.parentNode;
2608 }
2609
2610 // Lastly, move the split out all the split tags
2611 // to the new block as they should now be split properly.
2612 if(endNode){
2613 nodeToMove = endNode;
2614 if(nodeToMove.nodeType === 1 || (nodeToMove.nodeType === 3 && nodeToMove.nodeValue)){
2615 // Non-blank text and non-text nodes need to clear out that blank space
2616 // before moving the contents.
2617 newblock.innerHTML = "";
2618 }
2619 while(nodeToMove){
2620 tNode = nodeToMove.nextSibling;
2621 newblock.appendChild(nodeToMove);
2622 nodeToMove = tNode;
2623 }
2624 }
2625
2626 // We had intermediate tags, we have to now recreate them inbetween the split
2627 // and restore what styles, classnames, etc, we can.
2628 var newrange;
2629 if(tagList.length){
2630 tagData = tagList.pop();
2631 var newContTag = doc.createElement(tagData.tagName);
2632 if(tagData.cssText && newContTag.style){
2633 newContTag.style.cssText = tagData.cssText;
2634 }
2635 if(tagData.className){
2636 newContTag.className = tagData.className;
2637 }
2638 if(tagData.tagName === "FONT"){
2639 if(tagData.color){
2640 newContTag.color = tagData.color;
2641 }
2642 if(tagData.face){
2643 newContTag.face = tagData.face;
2644 }
2645 if(tagData.size){
2646 newContTag.size = tagData.size;
2647 }
2648 }
2649 domConstruct.place(newContTag, newblock, "before");
2650 while(tagList.length){
2651 tagData = tagList.pop();
2652 var newTgNode = doc.createElement(tagData.tagName);
2653 if(tagData.cssText && newTgNode.style){
2654 newTgNode.style.cssText = tagData.cssText;
2655 }
2656 if(tagData.className){
2657 newTgNode.className = tagData.className;
2658 }
2659 if(tagData.tagName === "FONT"){
2660 if(tagData.color){
2661 newTgNode.color = tagData.color;
2662 }
2663 if(tagData.face){
2664 newTgNode.face = tagData.face;
2665 }
2666 if(tagData.size){
2667 newTgNode.size = tagData.size;
2668 }
2669 }
2670 newContTag.appendChild(newTgNode);
2671 newContTag = newTgNode;
2672 }
2673
2674 // Okay, everything is theoretically split apart and removed from the content
2675 // so insert the dummy text to select, select it, then
2676 // clear to position cursor.
2677 sNode = doc.createTextNode(".");
2678 breaker.appendChild(sNode);
2679 newContTag.appendChild(sNode);
2680 newrange = rangeapi.create(this.window);
2681 newrange.setStart(sNode, 0);
2682 newrange.setEnd(sNode, sNode.length);
2683 selection.removeAllRanges();
2684 selection.addRange(newrange);
2685 this.selection.collapse(false);
2686 sNode.parentNode.innerHTML = "";
2687 }else{
2688 // No extra tags, so we have to insert a breaker point and rely
2689 // on filters to remove it later.
2690 breaker = doc.createElement("span");
2691 breaker.className = "ieFormatBreakerSpan";
2692 sNode = doc.createTextNode(".");
2693 breaker.appendChild(sNode);
2694 domConstruct.place(breaker, newblock, "before");
2695 newrange = rangeapi.create(this.window);
2696 newrange.setStart(sNode, 0);
2697 newrange.setEnd(sNode, sNode.length);
2698 selection.removeAllRanges();
2699 selection.addRange(newrange);
2700 this.selection.collapse(false);
2701 sNode.parentNode.innerHTML = "";
2702 }
2703 if(!newblock.firstChild){
2704 // Empty, we don't need it. Split was at end or similar
2705 // So, remove it.
2706 domConstruct.destroy(newblock);
2707 }
2708 return true;
2709 }
2710 }
2711 return false;
2712 }else{
2713 range = selection.getRangeAt(0);
2714 rs = range.startContainer;
2715 if(rs && rs.nodeType === 3){
2716 // Text node, we have to split it.
2717 var offset = range.startOffset;
2718 if(rs.length < offset){
2719 //We are not splitting the right node, try to locate the correct one
2720 ret = this._adjustNodeAndOffset(rs, offset);
2721 rs = ret.node;
2722 offset = ret.offset;
2723 }
2724 txt = rs.nodeValue;
2725 startNode = doc.createTextNode(txt.substring(0, offset));
2726 var endText = txt.substring(offset);
2727 if(endText !== ""){
2728 endNode = doc.createTextNode(txt.substring(offset));
2729 }
2730 // Create a space, we'll select and bold it, so
2731 // the whole word doesn't get bolded
2732 breaker = doc.createElement("span");
2733 sNode = doc.createTextNode(".");
2734 breaker.appendChild(sNode);
2735 if(startNode.length){
2736 domConstruct.place(startNode, rs, "after");
2737 }else{
2738 startNode = rs;
2739 }
2740 domConstruct.place(breaker, startNode, "after");
2741 if(endNode){
2742 domConstruct.place(endNode, breaker, "after");
2743 }
2744 domConstruct.destroy(rs);
2745 var newrange = rangeapi.create(this.window);
2746 newrange.setStart(sNode, 0);
2747 newrange.setEnd(sNode, sNode.length);
2748 selection.removeAllRanges();
2749 selection.addRange(newrange);
2750 doc.execCommand(command);
2751 domConstruct.place(breaker.firstChild, breaker, "before");
2752 domConstruct.destroy(breaker);
2753 newrange.setStart(sNode, 0);
2754 newrange.setEnd(sNode, sNode.length);
2755 selection.removeAllRanges();
2756 selection.addRange(newrange);
2757 this.selection.collapse(false);
2758 sNode.parentNode.innerHTML = "";
2759 return true;
2760 }
2761 }
2762 }else{
2763 return false;
2764 }
2765 },
2766
2767 _adaptIEList: function(command /*===== , argument =====*/){
2768 // summary:
2769 // This function handles normalizing the IE list behavior as
2770 // much as possible.
2771 // command:
2772 // The list command to execute.
2773 // argument:
2774 // Any additional argument.
2775 // tags:
2776 // private
2777 var selection = rangeapi.getSelection(this.window);
2778 if(selection.isCollapsed){
2779 // In the case of no selection, let's commonize the behavior and
2780 // make sure that it indents if needed.
2781 if(selection.rangeCount && !this.queryCommandValue(command)){
2782 var range = selection.getRangeAt(0);
2783 var sc = range.startContainer;
2784 if(sc && sc.nodeType == 3){
2785 // text node. Lets see if there is a node before it that isn't
2786 // some sort of breaker.
2787 if(!range.startOffset){
2788 // We're at the beginning of a text area. It may have been br split
2789 // Who knows? In any event, we must create the list manually
2790 // or IE may shove too much into the list element. It seems to
2791 // grab content before the text node too if it's br split.
2792 // Why can't IE work like everyone else?
2793 // This problem also happens on Edge.
2794
2795 // Create a space, we'll select and bold it, so
2796 // the whole word doesn't get bolded
2797 var lType = "ul";
2798 if(command === "insertorderedlist"){
2799 lType = "ol";
2800 }
2801 var list = this.document.createElement(lType);
2802 var li = domConstruct.create("li", null, list);
2803 domConstruct.place(list, sc, "before");
2804 // Move in the text node as part of the li.
2805 li.appendChild(sc);
2806 // We need a br after it or the enter key handler
2807 // sometimes throws errors.
2808 domConstruct.create("br", null, list, "after");
2809 // Okay, now lets move our cursor to the beginning.
2810 var newrange = rangeapi.create(this.window);
2811 newrange.setStart(sc, 0);
2812 newrange.setEnd(sc, sc.length);
2813 selection.removeAllRanges();
2814 selection.addRange(newrange);
2815 this.selection.collapse(true);
2816 return true;
2817 }
2818 }
2819 }
2820 }
2821 return false;
2822 },
2823
2824 _handleTextColorOrProperties: function(command, argument){
2825 // summary:
2826 // This function handles applying text color as best it is
2827 // able to do so when the selection is collapsed, making the
2828 // behavior cross-browser consistent. It also handles the name
2829 // and size for IE.
2830 // command:
2831 // The command.
2832 // argument:
2833 // Any additional arguments.
2834 // tags:
2835 // private
2836 var selection = rangeapi.getSelection(this.window);
2837 var doc = this.document;
2838 var rs, ret, range, txt, startNode, endNode, breaker, sNode;
2839 argument = argument || null;
2840 if(command && selection && selection.isCollapsed){
2841 if(selection.rangeCount){
2842 range = selection.getRangeAt(0);
2843 rs = range.startContainer;
2844 if(rs && rs.nodeType === 3){
2845 // Text node, we have to split it.
2846 var offset = range.startOffset;
2847 if(rs.length < offset){
2848 //We are not splitting the right node, try to locate the correct one
2849 ret = this._adjustNodeAndOffset(rs, offset);
2850 rs = ret.node;
2851 offset = ret.offset;
2852 }
2853 txt = rs.nodeValue;
2854 startNode = doc.createTextNode(txt.substring(0, offset));
2855 var endText = txt.substring(offset);
2856 if(endText !== ""){
2857 endNode = doc.createTextNode(txt.substring(offset));
2858 }
2859 // Create a space, we'll select and bold it, so
2860 // the whole word doesn't get bolded
2861 breaker = doc.createElement("span");
2862 sNode = doc.createTextNode(".");
2863 breaker.appendChild(sNode);
2864 // Create a junk node to avoid it trying to style the breaker.
2865 // This will get destroyed later.
2866 var extraSpan = doc.createElement("span");
2867 breaker.appendChild(extraSpan);
2868 if(startNode.length){
2869 domConstruct.place(startNode, rs, "after");
2870 }else{
2871 startNode = rs;
2872 }
2873 domConstruct.place(breaker, startNode, "after");
2874 if(endNode){
2875 domConstruct.place(endNode, breaker, "after");
2876 }
2877 domConstruct.destroy(rs);
2878 var newrange = rangeapi.create(this.window);
2879 newrange.setStart(sNode, 0);
2880 newrange.setEnd(sNode, sNode.length);
2881 selection.removeAllRanges();
2882 selection.addRange(newrange);
2883 if(has("webkit")){
2884 // WebKit is frustrating with positioning the cursor.
2885 // It stinks to have a selected space, but there really
2886 // isn't much choice here.
2887 var style = "color";
2888 if(command === "hilitecolor" || command === "backcolor"){
2889 style = "backgroundColor";
2890 }
2891 domStyle.set(breaker, style, argument);
2892 this.selection.remove();
2893 domConstruct.destroy(extraSpan);
2894 breaker.innerHTML = "&#160;"; // &nbsp;
2895 this.selection.selectElement(breaker);
2896 this.focus();
2897 }else{
2898 this.execCommand(command, argument);
2899 domConstruct.place(breaker.firstChild, breaker, "before");
2900 domConstruct.destroy(breaker);
2901 newrange.setStart(sNode, 0);
2902 newrange.setEnd(sNode, sNode.length);
2903 selection.removeAllRanges();
2904 selection.addRange(newrange);
2905 this.selection.collapse(false);
2906 sNode.parentNode.removeChild(sNode);
2907 }
2908 return true;
2909 }
2910 }
2911 }
2912 return false;
2913 },
2914
2915 _adjustNodeAndOffset: function(/*DomNode*/node, /*Int*/offset){
2916 // summary:
2917 // In the case there are multiple text nodes in a row the offset may not be within the node.
2918 // If the offset is larger than the node length, it will attempt to find
2919 // the next text sibling until it locates the text node in which the offset refers to
2920 // node:
2921 // The node to check.
2922 // offset:
2923 // The position to find within the text node
2924 // tags:
2925 // private.
2926 while(node.length < offset && node.nextSibling && node.nextSibling.nodeType === 3){
2927 //Adjust the offset and node in the case of multiple text nodes in a row
2928 offset = offset - node.length;
2929 node = node.nextSibling;
2930 }
2931 return {"node": node, "offset": offset};
2932 },
2933
2934 _tagNamesForCommand: function(command){
2935 // summary:
2936 // Function to return the tab names that are associated
2937 // with a particular style.
2938 // command: String
2939 // The command to return tags for.
2940 // tags:
2941 // private
2942 if(command === "bold"){
2943 return ["b", "strong"];
2944 }else if(command === "italic"){
2945 return ["i", "em"];
2946 }else if(command === "strikethrough"){
2947 return ["s", "strike"];
2948 }else if(command === "superscript"){
2949 return ["sup"];
2950 }else if(command === "subscript"){
2951 return ["sub"];
2952 }else if(command === "underline"){
2953 return ["u"];
2954 }
2955 return [];
2956 },
2957
2958 _stripBreakerNodes: function(/*DOMNode*/ node){
2959 // summary:
2960 // Function for stripping out the breaker spans inserted by the formatting command.
2961 // Registered as a filter for IE, handles the breaker spans needed to fix up
2962 // How bold/italic/etc, work when selection is collapsed (single cursor).
2963 if(!this.isLoaded){
2964 return;
2965 } // this method requires init to be complete
2966 query(".ieFormatBreakerSpan", node).forEach(function(b){
2967 while(b.firstChild){
2968 domConstruct.place(b.firstChild, b, "before");
2969 }
2970 domConstruct.destroy(b);
2971 });
2972 return node;
2973 },
2974
2975 _stripTrailingEmptyNodes: function(/*DOMNode*/ node){
2976 // summary:
2977 // Function for stripping trailing nodes without any text, excluding trailing nodes
2978 // like <img> or <div><img></div>, even though they don't have text either.
2979
2980 function isEmpty(node){
2981 // If not for old IE we could check for Element children by node.firstElementChild
2982 return (/^(p|div|br)$/i.test(node.nodeName) && node.children.length == 0 &&
2983 /^[\s\xA0]*$/.test(node.textContent || node.innerText || "")) ||
2984 (node.nodeType === 3/*text*/ && /^[\s\xA0]*$/.test(node.nodeValue));
2985 }
2986 while(node.lastChild && isEmpty(node.lastChild)){
2987 domConstruct.destroy(node.lastChild);
2988 }
2989
2990 return node;
2991 },
2992
2993 // Needed to support ToggleDir plugin. Intentionally not inside if(has("dojo-bidi")) block
2994 // so that (for backwards compatibility) ToggleDir plugin works even when has("dojo-bidi") is falsy.
2995 _setTextDirAttr: function(/*String*/ value){
2996 // summary:
2997 // Sets textDir attribute. Sets direction of editNode accordingly.
2998 this._set("textDir", value);
2999 this.onLoadDeferred.then(lang.hitch(this, function(){
3000 this.editNode.dir = value;
3001 }));
3002 }
3003 });
3004
3005 return RichText;
3006 });