1 define("dijit/Editor", [
2 "dojo/_base/array", // array.forEach
3 "dojo/_base/declare", // declare
4 "dojo/_base/Deferred", // Deferred
5 "dojo/i18n", // i18n.getLocalization
6 "dojo/dom-attr", // domAttr.set
7 "dojo/dom-class", // domClass.add
9 "dojo/dom-style", // domStyle.set, get
10 "dojo/_base/event", // event.stop
11 "dojo/keys", // keys.F1 keys.F15 keys.TAB
12 "dojo/_base/lang", // lang.getObject lang.hitch
13 "dojo/_base/sniff", // has("ie") has("mac") has("webkit")
14 "dojo/string", // string.substitute
15 "dojo/topic", // topic.publish()
16 "dojo/_base/window", // win.withGlobal
17 "./_base/focus", // dijit.getBookmark()
21 "./layout/_LayoutWidget",
22 "./form/ToggleButton",
24 "./_editor/plugins/EnterKeyHandling",
28 ".", // dijit._scopeName
29 "dojo/i18n!./_editor/nls/commands"
30 ], function(array, declare, Deferred, i18n, domAttr, domClass, domGeometry, domStyle,
31 event, keys, lang, has, string, topic, win,
32 focusBase, _Container, Toolbar, ToolbarSeparator, _LayoutWidget, ToggleButton,
33 _Plugin, EnterKeyHandling, html, rangeapi, RichText, dijit){
38 // A rich text Editing widget
40 var Editor = declare("dijit.Editor", RichText, {
42 // A rich text Editing widget
45 // This widget provides basic WYSIWYG editing features, based on the browser's
46 // underlying rich text editing capability, accompanied by a toolbar (`dijit.Toolbar`).
47 // A plugin model is available to extend the editor's capabilities as well as the
48 // the options available in the toolbar. Content generation may vary across
49 // browsers, and clipboard operations may have different results, to name
50 // a few limitations. Note: this widget should not be used with the HTML
51 // <TEXTAREA> tag -- see dijit._editor.RichText for details.
53 // plugins: [const] Object[]
54 // A list of plugin names (as strings) or instances (as objects)
57 // When declared in markup, it might look like:
58 // | plugins="['bold',{name:'dijit._editor.plugins.FontChoice', command:'fontName', generic:true}]"
61 // extraPlugins: [const] Object[]
62 // A list of extra plugin names which will be appended to plugins array
65 constructor: function(){
67 // Runs on widget initialization to setup arrays etc.
71 if(!lang.isArray(this.plugins)){
72 this.plugins=["undo","redo","|","cut","copy","paste","|","bold","italic","underline","strikethrough","|",
73 "insertOrderedList","insertUnorderedList","indent","outdent","|","justifyLeft","justifyRight","justifyCenter","justifyFull",
74 EnterKeyHandling /*, "createLink"*/];
78 this._editInterval = this.editActionInterval * 1000;
80 //IE will always lose focus when other element gets focus, while for FF and safari,
81 //when no iframe is used, focus will be lost whenever another element gets focus.
82 //For IE, we can connect to onBeforeDeactivate, which will be called right before
83 //the focus is lost, so we can obtain the selected range. For other browsers,
84 //no equivalent of onBeforeDeactivate, so we need to do two things to make sure
85 //selection is properly saved before focus is lost: 1) when user clicks another
86 //element in the page, in which case we listen to mousedown on the entire page and
87 //see whether user clicks out of a focus editor, if so, save selection (focus will
88 //only lost after onmousedown event is fired, so we can obtain correct caret pos.)
89 //2) when user tabs away from the editor, which is handled in onKeyDown below.
91 this.events.push("onBeforeDeactivate");
92 this.events.push("onBeforeActivate");
96 postMixInProperties: function(){
98 // Extension to make sure a deferred is in place before certain functions
99 // execute, like making sure all the plugins are properly inserted.
101 // Set up a deferred so that the value isn't applied to the editor
102 // until all the plugins load, needed to avoid timing condition
103 // reported in #10537.
104 this.setValueDeferred = new Deferred();
105 this.inherited(arguments);
108 postCreate: function(){
109 //for custom undo/redo, if enabled.
110 this._steps=this._steps.slice(0);
111 this._undoedSteps=this._undoedSteps.slice(0);
113 if(lang.isArray(this.extraPlugins)){
114 this.plugins=this.plugins.concat(this.extraPlugins);
117 this.inherited(arguments);
119 this.commands = i18n.getLocalization("dijit._editor", "commands", this.lang);
122 // if we haven't been assigned a toolbar, create one
123 this.toolbar = new Toolbar({
127 this.header.appendChild(this.toolbar.domNode);
130 array.forEach(this.plugins, this.addPlugin, this);
132 // Okay, denote the value can now be set.
133 this.setValueDeferred.callback(true);
135 domClass.add(this.iframe.parentNode, "dijitEditorIFrameContainer");
136 domClass.add(this.iframe, "dijitEditorIFrame");
137 domAttr.set(this.iframe, "allowTransparency", true);
140 // Disable selecting the entire editor by inadvertent double-clicks.
141 // on buttons, title bar, etc. Otherwise clicking too fast on
142 // a button such as undo/redo selects the entire editor.
143 domStyle.set(this.domNode, "KhtmlUserSelect", "none");
145 this.toolbar.startup();
146 this.onNormalizedDisplayChanged(); //update toolbar button status
149 array.forEach(this._plugins, function(p){
155 this.toolbar.destroyRecursive();
157 this.inherited(arguments);
159 addPlugin: function(/*String||Object||Function*/plugin, /*Integer?*/index){
161 // takes a plugin name as a string or a plugin instance and
162 // adds it to the toolbar and associates it with this editor
163 // instance. The resulting plugin is added to the Editor's
164 // plugins array. If index is passed, it's placed in the plugins
165 // array at that index. No big magic, but a nice helper for
166 // passing in plugin names via markup.
168 // plugin: String, args object, plugin instance, or plugin constructor
171 // This object will be passed to the plugin constructor
174 // Used when creating an instance from
175 // something already in this.plugins. Ensures that the new
176 // instance is assigned to this.plugins at that index.
177 var args=lang.isString(plugin)?{name:plugin}:lang.isFunction(plugin)?{ctor:plugin}:plugin;
179 var o={"args":args,"plugin":null,"editor":this};
181 // search registry for a plugin factory matching args.name, if it's not there then
182 // fallback to 1.0 API:
183 // ask all loaded plugin modules to fill in o.plugin if they can (ie, if they implement args.name)
184 // remove fallback for 2.0.
185 if(_Plugin.registry[args.name]){
186 o.plugin = _Plugin.registry[args.name](args);
188 topic.publish(dijit._scopeName + ".Editor.getPlugin", o); // publish
192 var pc = args.ctor || lang.getObject(args.name);
194 o.plugin=new pc(args);
198 console.warn('Cannot find plugin',plugin);
203 if(arguments.length > 1){
204 this._plugins[index] = plugin;
206 this._plugins.push(plugin);
208 plugin.setEditor(this);
209 if(lang.isFunction(plugin.setToolbar)){
210 plugin.setToolbar(this.toolbar);
214 //the following 2 functions are required to make the editor play nice under a layout widget, see #4070
216 resize: function(size){
218 // Resize the editor to the specified size, see `dijit.layout._LayoutWidget.resize`
220 // we've been given a height/width for the entire editor (toolbar + contents), calls layout()
221 // to split the allocated size between the toolbar and the contents
222 _LayoutWidget.prototype.resize.apply(this, arguments);
226 // do nothing, the editor is already laid out correctly. The user has probably specified
227 // the height parameter, which was used to set a size on the iframe
233 // Called from `dijit.layout._LayoutWidget.resize`. This shouldn't be called directly
237 // Converts the iframe (or rather the <div> surrounding it) to take all the available space
238 // except what's needed for the header (toolbars) and footer (breadcrumbs, etc).
239 // A class was added to the iframe container and some themes style it, so we have to
240 // calc off the added margins and padding too. See tracker: #10662
241 var areaHeight = (this._contentBox.h -
242 (this.getHeaderHeight() + this.getFooterHeight() +
243 domGeometry.getPadBorderExtents(this.iframe.parentNode).h +
244 domGeometry.getMarginExtents(this.iframe.parentNode).h));
245 this.editingArea.style.height = areaHeight + "px";
247 this.iframe.style.height="100%";
249 this._layoutMode = true;
252 _onIEMouseDown: function(/*Event*/ e){
254 // IE only to prevent 2 clicks to focus
257 var outsideClientArea;
258 // IE 8's componentFromPoint is broken, which is a shame since it
259 // was smaller code, but oh well. We have to do this brute force
260 // to detect if the click was scroller or not.
261 var b = this.document.body;
262 var clientWidth = b.clientWidth;
263 var clientHeight = b.clientHeight;
264 var clientLeft = b.clientLeft;
265 var offsetWidth = b.offsetWidth;
266 var offsetHeight = b.offsetHeight;
267 var offsetLeft = b.offsetLeft;
269 //Check for vertical scroller click.
270 if(/^rtl$/i.test(b.dir || "")){
271 if(clientWidth < offsetWidth && e.x > clientWidth && e.x < offsetWidth){
272 // Check the click was between width and offset width, if so, scroller
273 outsideClientArea = true;
276 // RTL mode, we have to go by the left offsets.
277 if(e.x < clientLeft && e.x > offsetLeft){
278 // Check the click was between width and offset width, if so, scroller
279 outsideClientArea = true;
282 if(!outsideClientArea){
283 // Okay, might be horiz scroller, check that.
284 if(clientHeight < offsetHeight && e.y > clientHeight && e.y < offsetHeight){
285 // Horizontal scroller.
286 outsideClientArea = true;
289 if(!outsideClientArea){
290 delete this._cursorToStart; // Remove the force to cursor to start position.
291 delete this._savedSelection; // new mouse position overrides old selection
292 if(e.target.tagName == "BODY"){
293 setTimeout(lang.hitch(this, "placeCursorAtEnd"), 0);
295 this.inherited(arguments);
298 onBeforeActivate: function(){
299 this._restoreSelection();
301 onBeforeDeactivate: function(e){
303 // Called on IE right before focus is lost. Saves the selected range.
307 this.endEditing(true);
309 //in IE, the selection will be lost when other elements get focus,
310 //let's save focus before the editor is deactivated
311 if(e.target.tagName != "BODY"){
312 this._saveSelection();
314 //console.log('onBeforeDeactivate',this);
317 /* beginning of custom undo/redo support */
319 // customUndo: Boolean
320 // Whether we shall use custom undo/redo support instead of the native
321 // browser support. By default, we now use custom undo. It works better
322 // than native browser support and provides a consistent behavior across
323 // browsers with a minimal performance hit. We already had the hit on
324 // the slowest browser, IE, anyway.
327 // editActionInterval: Integer
328 // When using customUndo, not every keystroke will be saved as a step.
329 // Instead typing (including delete) will be grouped together: after
330 // a user stops typing for editActionInterval seconds, a step will be
331 // saved; if a user resume typing within editActionInterval seconds,
332 // the timeout will be restarted. By default, editActionInterval is 3
334 editActionInterval: 3,
336 beginEditing: function(cmd){
338 // Called to note that the user has started typing alphanumeric characters, if it's not already noted.
339 // Deals with saving undo; see editActionInterval parameter.
342 if(!this._inEditing){
343 this._inEditing=true;
344 this._beginEditing(cmd);
346 if(this.editActionInterval>0){
348 clearTimeout(this._editTimer);
350 this._editTimer = setTimeout(lang.hitch(this, this.endEditing), this._editInterval);
354 // TODO: declaring these in the prototype is meaningless, just create in the constructor/postCreate
358 execCommand: function(cmd){
360 // Main handler for executing any commands to the editor, like paste, bold, etc.
361 // Called by plugins, but not meant to be called by end users.
364 if(this.customUndo && (cmd == 'undo' || cmd == 'redo')){
369 this._beginEditing();
371 var r = this.inherited(arguments);
379 _pasteImpl: function(){
381 // Over-ride of paste command control to make execCommand cleaner
384 return this._clipboardCommand("paste");
387 _cutImpl: function(){
389 // Over-ride of cut command control to make execCommand cleaner
392 return this._clipboardCommand("cut");
395 _copyImpl: function(){
397 // Over-ride of copy command control to make execCommand cleaner
400 return this._clipboardCommand("copy");
403 _clipboardCommand: function(cmd){
405 // Function to handle processing clipboard commands (or at least try to).
410 // Try to exec the superclass exec-command and see if it works.
411 r = this.document.execCommand(cmd, false, null);
412 if(has("webkit") && !r){ //see #4598: webkit does not guarantee clipboard support from js
413 throw { code: 1011 }; // throw an object like Mozilla's error
416 //TODO: when else might we get an exception? Do we need the Mozilla test below?
417 if(e.code == 1011 /* Mozilla: service denied */){
418 // Warn user of platform limitation. Cannot programmatically access clipboard. See ticket #4136
419 var sub = string.substitute,
420 accel = {cut:'X', copy:'C', paste:'V'};
421 alert(sub(this.commands.systemShortcut,
422 [this.commands[cmd], sub(this.commands[has("mac") ? 'appleKey' : 'ctrlKey'], [accel[cmd]])]));
429 queryCommandEnabled: function(cmd){
431 // Returns true if specified editor command is enabled.
432 // Used by the plugins to know when to highlight/not highlight buttons.
435 if(this.customUndo && (cmd == 'undo' || cmd == 'redo')){
436 return cmd == 'undo' ? (this._steps.length > 1) : (this._undoedSteps.length > 0);
438 return this.inherited(arguments);
441 _moveToBookmark: function(b){
443 // Selects the text specified in bookmark b
446 var bookmark = b.mark;
448 var col = b.isCollapsed;
449 var r, sNode, eNode, sel;
452 if(lang.isArray(mark)){
453 //IE CONTROL, have to use the native bookmark.
455 array.forEach(mark,function(n){
456 bookmark.push(rangeapi.getNode(n,this.editNode));
458 win.withGlobal(this.window,'moveToBookmark',dijit,[{mark: bookmark, isCollapsed: col}]);
460 if(mark.startContainer && mark.endContainer){
461 // Use the pseudo WC3 range API. This works better for positions
462 // than the IE native bookmark code.
463 sel = rangeapi.getSelection(this.window);
464 if(sel && sel.removeAllRanges){
465 sel.removeAllRanges();
466 r = rangeapi.create(this.window);
467 sNode = rangeapi.getNode(mark.startContainer,this.editNode);
468 eNode = rangeapi.getNode(mark.endContainer,this.editNode);
470 // Okay, we believe we found the position, so add it into the selection
471 // There are cases where it may not be found, particularly in undo/redo, when
472 // IE changes the underlying DOM on us (wraps text in a <p> tag or similar.
473 // So, in those cases, don't bother restoring selection.
474 r.setStart(sNode,mark.startOffset);
475 r.setEnd(eNode,mark.endOffset);
482 sel = rangeapi.getSelection(this.window);
483 if(sel && sel.removeAllRanges){
484 sel.removeAllRanges();
485 r = rangeapi.create(this.window);
486 sNode = rangeapi.getNode(mark.startContainer,this.editNode);
487 eNode = rangeapi.getNode(mark.endContainer,this.editNode);
489 // Okay, we believe we found the position, so add it into the selection
490 // There are cases where it may not be found, particularly in undo/redo, when
491 // formatting as been done and so on, so don't restore selection then.
492 r.setStart(sNode,mark.startOffset);
493 r.setEnd(eNode,mark.endOffset);
500 _changeToStep: function(from, to){
502 // Reverts editor to "to" setting, from the undo stack.
505 this.setValue(to.text);
508 this._moveToBookmark(b);
512 // Handler for editor undo (ex: ctrl-z) operation
515 //console.log('undo');
517 if(!this._undoRedoActive){
518 this._undoRedoActive = true;
519 this.endEditing(true);
520 var s=this._steps.pop();
521 if(s && this._steps.length>0){
523 this._changeToStep(s,this._steps[this._steps.length-1]);
524 this._undoedSteps.push(s);
525 this.onDisplayChanged();
526 delete this._undoRedoActive;
529 delete this._undoRedoActive;
535 // Handler for editor redo (ex: ctrl-y) operation
538 //console.log('redo');
540 if(!this._undoRedoActive){
541 this._undoRedoActive = true;
542 this.endEditing(true);
543 var s=this._undoedSteps.pop();
544 if(s && this._steps.length>0){
546 this._changeToStep(this._steps[this._steps.length-1],s);
548 this.onDisplayChanged();
551 delete this._undoRedoActive;
555 endEditing: function(ignore_caret){
557 // Called to note that the user has stopped typing alphanumeric characters, if it's not already noted.
558 // Deals with saving undo; see editActionInterval parameter.
562 clearTimeout(this._editTimer);
565 this._endEditing(ignore_caret);
566 this._inEditing=false;
570 _getBookmark: function(){
572 // Get the currently selected text
575 var b=win.withGlobal(this.window,focusBase.getBookmark);
580 // Try to use the pseudo range API on IE for better accuracy.
581 var sel = rangeapi.getSelection(this.window);
582 if(!lang.isArray(mark)){
586 range = sel.getRangeAt(0);
589 b.mark = range.cloneRange();
591 b.mark = win.withGlobal(this.window,focusBase.getBookmark);
595 // Control ranges (img, table, etc), handle differently.
596 array.forEach(b.mark,function(n){
597 tmp.push(rangeapi.getIndex(n,this.editNode).o);
603 if(b.mark && b.mark.startContainer){
604 tmp=rangeapi.getIndex(b.mark.startContainer,this.editNode).o;
605 b.mark={startContainer:tmp,
606 startOffset:b.mark.startOffset,
607 endContainer:b.mark.endContainer===b.mark.startContainer?tmp:rangeapi.getIndex(b.mark.endContainer,this.editNode).o,
608 endOffset:b.mark.endOffset};
616 _beginEditing: function(){
618 // Called when the user starts typing alphanumeric characters.
619 // Deals with saving undo; see editActionInterval parameter.
622 if(this._steps.length === 0){
623 // You want to use the editor content without post filtering
624 // to make sure selection restores right for the 'initial' state.
625 // and undo is called. So not using this.value, as it was 'processed'
626 // and the line-up for selections may have been altered.
627 this._steps.push({'text':html.getChildrenHtml(this.editNode),'bookmark':this._getBookmark()});
630 _endEditing: function(){
632 // Called when the user stops typing alphanumeric characters.
633 // Deals with saving undo; see editActionInterval parameter.
636 // Avoid filtering to make sure selections restore.
637 var v = html.getChildrenHtml(this.editNode);
639 this._undoedSteps=[];//clear undoed steps
640 this._steps.push({text: v, bookmark: this._getBookmark()});
642 onKeyDown: function(e){
644 // Handler for onkeydown event.
648 //We need to save selection if the user TAB away from this editor
649 //no need to call _saveSelection for IE, as that will be taken care of in onBeforeDeactivate
650 if(!has("ie") && !this.iframe && e.keyCode == keys.TAB && !this.tabIndent){
651 this._saveSelection();
653 if(!this.customUndo){
654 this.inherited(arguments);
658 if(e.ctrlKey && !e.altKey){//undo and redo only if the special right Alt + z/y are not pressed #5892
659 if(k == 90 || k == 122){ //z
663 }else if(k == 89 || k == 121){ //y
669 this.inherited(arguments);
679 if(e.ctrlKey && !e.altKey && !e.metaKey){
680 this.endEditing();//end current typing step if any
682 this.beginEditing('cut');
683 //use timeout to trigger after the cut is complete
684 setTimeout(lang.hitch(this, this.endEditing), 1);
686 this.beginEditing('paste');
687 //use timeout to trigger after the paste is complete
688 setTimeout(lang.hitch(this, this.endEditing), 1);
694 if(!e.ctrlKey && !e.altKey && !e.metaKey && (e.keyCode<keys.F1 || e.keyCode>keys.F15)){
703 case keys.DOWN_ARROW:
704 case keys.LEFT_ARROW:
705 case keys.RIGHT_ARROW:
710 this.endEditing(true);
712 //maybe ctrl+backspace/delete, so don't endEditing when ctrl is pressed
721 // Called from focus manager when focus has moved away from this editor
725 //this._saveSelection();
726 this.inherited(arguments);
727 this.endEditing(true);
729 _saveSelection: function(){
731 // Save the currently selected text in _savedSelection attribute
735 this._savedSelection=this._getBookmark();
736 }catch(e){ /* Squelch any errors that occur if selection save occurs due to being hidden simultaneously. */}
738 _restoreSelection: function(){
740 // Re-select the text specified in _savedSelection attribute;
741 // see _saveSelection().
744 if(this._savedSelection){
745 // Clear off cursor to start, we're deliberately going to a selection.
746 delete this._cursorToStart;
747 // only restore the selection if the current range is collapsed
748 // if not collapsed, then it means the editor does not lose
749 // selection and there is no need to restore it
750 if(win.withGlobal(this.window,'isCollapsed',dijit)){
751 this._moveToBookmark(this._savedSelection);
753 delete this._savedSelection;
759 // Handler for when editor is clicked
762 this.endEditing(true);
763 this.inherited(arguments);
766 replaceValue: function(/*String*/ html){
768 // over-ride of replaceValue to support custom undo and stack maintenance.
771 if(!this.customUndo){
772 this.inherited(arguments);
779 html = " "; //
787 _setDisabledAttr: function(/*Boolean*/ value){
788 var disableFunc = lang.hitch(this, function(){
789 if((!this.disabled && value) || (!this._buttonEnabledPlugins && value)){
790 // Disable editor: disable all enabled buttons and remember that list
791 array.forEach(this._plugins, function(p){
792 p.set("disabled", true);
794 }else if(this.disabled && !value){
795 // Restore plugins to being active.
796 array.forEach(this._plugins, function(p){
797 p.set("disabled", false);
801 this.setValueDeferred.addCallback(disableFunc);
802 this.inherited(arguments);
805 _setStateClass: function(){
807 this.inherited(arguments);
809 // Let theme set the editor's text color based on editor enabled/disabled state.
810 // We need to jump through hoops because the main document (where the theme CSS is)
811 // is separate from the iframe's document.
812 if(this.document && this.document.body){
813 domStyle.set(this.document.body, "color", domStyle.get(this.iframe, "color"));
815 }catch(e){ /* Squelch any errors caused by focus change if hidden during a state change */}
819 // Register the "default plugins", ie, the built-in editor commands
820 function simplePluginFactory(args){
821 return new _Plugin({ command: args.name });
823 function togglePluginFactory(args){
824 return new _Plugin({ buttonClass: ToggleButton, command: args.name });
826 lang.mixin(_Plugin.registry, {
827 "undo": simplePluginFactory,
828 "redo": simplePluginFactory,
829 "cut": simplePluginFactory,
830 "copy": simplePluginFactory,
831 "paste": simplePluginFactory,
832 "insertOrderedList": simplePluginFactory,
833 "insertUnorderedList": simplePluginFactory,
834 "indent": simplePluginFactory,
835 "outdent": simplePluginFactory,
836 "justifyCenter": simplePluginFactory,
837 "justifyFull": simplePluginFactory,
838 "justifyLeft": simplePluginFactory,
839 "justifyRight": simplePluginFactory,
840 "delete": simplePluginFactory,
841 "selectAll": simplePluginFactory,
842 "removeFormat": simplePluginFactory,
843 "unlink": simplePluginFactory,
844 "insertHorizontalRule": simplePluginFactory,
846 "bold": togglePluginFactory,
847 "italic": togglePluginFactory,
848 "underline": togglePluginFactory,
849 "strikethrough": togglePluginFactory,
850 "subscript": togglePluginFactory,
851 "superscript": togglePluginFactory,
854 return new _Plugin({ button: new ToolbarSeparator(), setEditor: function(editor){this.editor = editor;}});