Fix #7586 - more events for editor
[roojs1] / Roo / form / HtmlEditor.js
1 //<script type="text/javascript">
2
3 /*
4  * Ext JS Library 1.1.1
5  * Copyright(c) 2006-2007, Ext JS, LLC.
6  * Licence LGPL
7  * 
8  */
9  
10  
11 Roo.form.HtmlEditor = function(config){
12     
13     
14     
15     Roo.form.HtmlEditor.superclass.constructor.call(this, config);
16     
17     if (!this.toolbars) {
18         this.toolbars = [];
19     }
20     this.editorcore = new Roo.HtmlEditorCore(Roo.apply({ owner : this} , config));
21     
22     
23 };
24
25 /**
26  * @class Roo.form.HtmlEditor
27  * @extends Roo.form.Field
28  * Provides a lightweight HTML Editor component.
29  *
30  * This has been tested on Fireforx / Chrome.. IE may not be so great..
31  * 
32  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
33  * supported by this editor.</b><br/><br/>
34  * An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
35  * any element that has display set to 'none' can cause problems in Safari and Firefox.<br/><br/>
36  */
37 Roo.extend(Roo.form.HtmlEditor, Roo.form.Field, {
38     /**
39      * @cfg {Boolean} clearUp
40      */
41     clearUp : true,
42       /**
43      * @cfg {Array} toolbars Array of toolbars. - defaults to just the Standard one
44      */
45     toolbars : false,
46    
47      /**
48      * @cfg {String} resizable  's' or 'se' or 'e' - wrapps the element in a
49      *                        Roo.resizable.
50      */
51     resizable : false,
52      /**
53      * @cfg {Number} height (in pixels)
54      */   
55     height: 300,
56    /**
57      * @cfg {Number} width (in pixels)
58      */   
59     width: 500,
60     
61     /**
62      * @cfg {Array} stylesheets url of stylesheets. set to [] to disable stylesheets - this is usally a good idea  rootURL + '/roojs1/css/undoreset.css',   .
63      * 
64      */
65     stylesheets: false,
66     
67     
68      /**
69      * @cfg {Array} blacklist of css styles style attributes (blacklist overrides whitelist)
70      * 
71      */
72     cblack: false,
73     /**
74      * @cfg {Array} whitelist of css styles style attributes (blacklist overrides whitelist)
75      * 
76      */
77     cwhite: false,
78     
79      /**
80      * @cfg {Array} blacklist of html tags - in addition to standard blacklist.
81      * 
82      */
83     black: false,
84     /**
85      * @cfg {Array} whitelist of html tags - in addition to statndard whitelist
86      * 
87      */
88     white: false,
89     /**
90      * @cfg {boolean} allowComments - default false - allow comments in HTML source - by default they are stripped - if you are editing email you may need this.
91      */
92     allowComments: false,
93     /**
94      * @cfg {boolean} enableBlocks - default true - if the block editor (table and figure should be enabled)
95      */
96     enableBlocks : true,
97     
98     /**
99      * @cfg {boolean} autoClean - default true - loading and saving will remove quite a bit of formating,
100      *         if you are doing an email editor, this probably needs disabling, it's designed
101      */
102     autoClean: true,
103     /**
104      * @cfg {string} bodyCls default '' default classes to add to body of editable area - usually undoreset is a good start..
105      */
106     bodyCls : '',
107     /**
108      * @cfg {String} language default en - language of text (usefull for rtl languages)
109      * 
110      */
111     language: 'en',
112     
113      
114     // id of frame..
115     frameId: false,
116     
117     // private properties
118     validationEvent : false,
119     deferHeight: true,
120     initialized : false,
121     activated : false,
122     
123     onFocus : Roo.emptyFn,
124     iframePad:3,
125     hideMode:'offsets',
126     
127     actionMode : 'container', // defaults to hiding it...
128     
129     defaultAutoCreate : { // modified by initCompnoent..
130         tag: "textarea",
131         style:"width:500px;height:300px;",
132         autocomplete: "new-password"
133     },
134
135     // private
136     initComponent : function(){
137         this.addEvents({
138             /**
139              * @event initialize
140              * Fires when the editor is fully initialized (including the iframe)
141              * @param {HtmlEditor} this
142              */
143             initialize: true,
144             /**
145              * @event activate
146              * Fires when the editor is first receives the focus. Any insertion must wait
147              * until after this event.
148              * @param {HtmlEditor} this
149              */
150             activate: true,
151              /**
152              * @event beforesync
153              * Fires before the textarea is updated with content from the editor iframe. Return false
154              * to cancel the sync.
155              * @param {HtmlEditor} this
156              * @param {String} html
157              */
158             beforesync: true,
159              /**
160              * @event beforepush
161              * Fires before the iframe editor is updated with content from the textarea. Return false
162              * to cancel the push.
163              * @param {HtmlEditor} this
164              * @param {String} html
165              */
166             beforepush: true,
167              /**
168              * @event sync
169              * Fires when the textarea is updated with content from the editor iframe.
170              * @param {HtmlEditor} this
171              * @param {String} html
172              */
173             sync: true,
174              /**
175              * @event push
176              * Fires when the iframe editor is updated with content from the textarea.
177              * @param {HtmlEditor} this
178              * @param {String} html
179              */
180             push: true,
181              /**
182              * @event editmodechange
183              * Fires when the editor switches edit modes
184              * @param {HtmlEditor} this
185              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
186              */
187             editmodechange: true,
188             /**
189              * @event editorevent
190              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
191              * @param {HtmlEditor} this
192              */
193             editorevent: true,
194             /**
195              * @event firstfocus
196              * Fires when on first focus - needed by toolbars..
197              * @param {HtmlEditor} this
198              */
199             firstfocus: true,
200             /**
201              * @event autosave
202              * Auto save the htmlEditor value as a file into Events
203              * @param {HtmlEditor} this
204              */
205             autosave: true,
206             /**
207              * @event savedpreview
208              * preview the saved version of htmlEditor
209              * @param {HtmlEditor} this
210              */
211             savedpreview: true,
212             
213             /**
214             * @event stylesheetsclick
215             * Fires when press the Sytlesheets button
216             * @param {Roo.HtmlEditorCore} this
217             */
218             stylesheetsclick: true,
219             /**
220             * @event paste
221             * Fires when press user pastes into the editor
222             * @param {Roo.HtmlEditorCore} this
223             */
224             paste: true,
225             
226         });
227         this.defaultAutoCreate =  {
228             tag: "textarea",
229             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
230             autocomplete: "new-password"
231         };
232     },
233
234     /**
235      * Protected method that will not generally be called directly. It
236      * is called when the editor creates its toolbar. Override this method if you need to
237      * add custom toolbar buttons.
238      * @param {HtmlEditor} editor
239      */
240     createToolbar : function(editor){
241         Roo.log("create toolbars");
242         if (!editor.toolbars || !editor.toolbars.length) {
243             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
244         }
245         
246         for (var i =0 ; i < editor.toolbars.length;i++) {
247             editor.toolbars[i] = Roo.factory(
248                     typeof(editor.toolbars[i]) == 'string' ?
249                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
250                 Roo.form.HtmlEditor);
251             editor.toolbars[i].init(editor);
252         }
253          
254         
255     },
256     /**
257      * get the Context selected node
258      * @returns {DomElement|boolean} selected node if active or false if none
259      * 
260      */
261     getSelectedNode : function()
262     {
263         if (this.toolbars.length < 2 || !this.toolbars[1].tb) {
264             return false;
265         }
266         return this.toolbars[1].tb.selectedNode;
267     
268     },
269     // private
270     onRender : function(ct, position)
271     {
272         var _t = this;
273         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
274         
275         this.wrap = this.el.wrap({
276             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
277         });
278         
279         this.editorcore.onRender(ct, position);
280          
281         if (this.resizable) {
282             this.resizeEl = new Roo.Resizable(this.wrap, {
283                 pinned : true,
284                 wrap: true,
285                 dynamic : true,
286                 minHeight : this.height,
287                 height: this.height,
288                 handles : this.resizable,
289                 width: this.width,
290                 listeners : {
291                     resize : function(r, w, h) {
292                         _t.onResize(w,h); // -something
293                     }
294                 }
295             });
296             
297         }
298         this.createToolbar(this);
299        
300         
301         if(!this.width){
302             this.setSize(this.wrap.getSize());
303         }
304         if (this.resizeEl) {
305             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
306             // should trigger onReize..
307         }
308         
309         this.keyNav = new Roo.KeyNav(this.el, {
310             
311             "tab" : function(e){
312                 e.preventDefault();
313                 
314                 var value = this.getValue();
315                 
316                 var start = this.el.dom.selectionStart;
317                 var end = this.el.dom.selectionEnd;
318                 
319                 if(!e.shiftKey){
320                     
321                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
322                     this.el.dom.setSelectionRange(end + 1, end + 1);
323                     return;
324                 }
325                 
326                 var f = value.substring(0, start).split("\t");
327                 
328                 if(f.pop().length != 0){
329                     return;
330                 }
331                 
332                 this.setValue(f.join("\t") + value.substring(end));
333                 this.el.dom.setSelectionRange(start - 1, start - 1);
334                 
335             },
336             
337             "home" : function(e){
338                 e.preventDefault();
339                 
340                 var curr = this.el.dom.selectionStart;
341                 var lines = this.getValue().split("\n");
342                 
343                 if(!lines.length){
344                     return;
345                 }
346                 
347                 if(e.ctrlKey){
348                     this.el.dom.setSelectionRange(0, 0);
349                     return;
350                 }
351                 
352                 var pos = 0;
353                 
354                 for (var i = 0; i < lines.length;i++) {
355                     pos += lines[i].length;
356                     
357                     if(i != 0){
358                         pos += 1;
359                     }
360                     
361                     if(pos < curr){
362                         continue;
363                     }
364                     
365                     pos -= lines[i].length;
366                     
367                     break;
368                 }
369                 
370                 if(!e.shiftKey){
371                     this.el.dom.setSelectionRange(pos, pos);
372                     return;
373                 }
374                 
375                 this.el.dom.selectionStart = pos;
376                 this.el.dom.selectionEnd = curr;
377             },
378             
379             "end" : function(e){
380                 e.preventDefault();
381                 
382                 var curr = this.el.dom.selectionStart;
383                 var lines = this.getValue().split("\n");
384                 
385                 if(!lines.length){
386                     return;
387                 }
388                 
389                 if(e.ctrlKey){
390                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
391                     return;
392                 }
393                 
394                 var pos = 0;
395                 
396                 for (var i = 0; i < lines.length;i++) {
397                     
398                     pos += lines[i].length;
399                     
400                     if(i != 0){
401                         pos += 1;
402                     }
403                     
404                     if(pos < curr){
405                         continue;
406                     }
407                     
408                     break;
409                 }
410                 
411                 if(!e.shiftKey){
412                     this.el.dom.setSelectionRange(pos, pos);
413                     return;
414                 }
415                 
416                 this.el.dom.selectionStart = curr;
417                 this.el.dom.selectionEnd = pos;
418             },
419
420             scope : this,
421
422             doRelay : function(foo, bar, hname){
423                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
424             },
425
426             forceKeyDown: true
427         });
428         
429 //        if(this.autosave && this.w){
430 //            this.autoSaveFn = setInterval(this.autosave, 1000);
431 //        }
432     },
433
434     // private
435     onResize : function(w, h)
436     {
437         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
438         var ew = false;
439         var eh = false;
440         
441         if(this.el ){
442             if(typeof w == 'number'){
443                 var aw = w - this.wrap.getFrameWidth('lr');
444                 this.el.setWidth(this.adjustWidth('textarea', aw));
445                 ew = aw;
446             }
447             if(typeof h == 'number'){
448                 var tbh = 0;
449                 for (var i =0; i < this.toolbars.length;i++) {
450                     // fixme - ask toolbars for heights?
451                     tbh += this.toolbars[i].tb.el.getHeight();
452                     if (this.toolbars[i].footer) {
453                         tbh += this.toolbars[i].footer.el.getHeight();
454                     }
455                 }
456                 
457                 
458                 
459                 
460                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
461                 ah -= 5; // knock a few pixes off for look..
462 //                Roo.log(ah);
463                 this.el.setHeight(this.adjustWidth('textarea', ah));
464                 var eh = ah;
465             }
466         }
467         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
468         this.editorcore.onResize(ew,eh);
469         
470     },
471
472     /**
473      * Toggles the editor between standard and source edit mode.
474      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
475      */
476     toggleSourceEdit : function(sourceEditMode)
477     {
478         this.editorcore.toggleSourceEdit(sourceEditMode);
479         
480         if(this.editorcore.sourceEditMode){
481             Roo.log('editor - showing textarea');
482             
483 //            Roo.log('in');
484 //            Roo.log(this.syncValue());
485             this.editorcore.syncValue();
486             this.el.removeClass('x-hidden');
487             this.el.dom.removeAttribute('tabIndex');
488             this.el.focus();
489             this.el.dom.scrollTop = 0;
490             
491             
492             for (var i = 0; i < this.toolbars.length; i++) {
493                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
494                     this.toolbars[i].tb.hide();
495                     this.toolbars[i].footer.hide();
496                 }
497             }
498             
499         }else{
500             Roo.log('editor - hiding textarea');
501 //            Roo.log('out')
502 //            Roo.log(this.pushValue()); 
503             this.editorcore.pushValue();
504             
505             this.el.addClass('x-hidden');
506             this.el.dom.setAttribute('tabIndex', -1);
507             
508             for (var i = 0; i < this.toolbars.length; i++) {
509                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
510                     this.toolbars[i].tb.show();
511                     this.toolbars[i].footer.show();
512                 }
513             }
514             
515             //this.deferFocus();
516         }
517         
518         this.setSize(this.wrap.getSize());
519         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
520         
521         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
522     },
523  
524     // private (for BoxComponent)
525     adjustSize : Roo.BoxComponent.prototype.adjustSize,
526
527     // private (for BoxComponent)
528     getResizeEl : function(){
529         return this.wrap;
530     },
531
532     // private (for BoxComponent)
533     getPositionEl : function(){
534         return this.wrap;
535     },
536
537     // private
538     initEvents : function(){
539         this.originalValue = this.getValue();
540     },
541
542     /**
543      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
544      * @method
545      */
546     markInvalid : Roo.emptyFn,
547     /**
548      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
549      * @method
550      */
551     clearInvalid : Roo.emptyFn,
552
553     setValue : function(v){
554         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
555         this.editorcore.pushValue();
556     },
557
558     /**
559      * update the language in the body - really done by core
560      * @param {String} language - eg. en / ar / zh-CN etc..
561      */
562     updateLanguage : function(lang)
563     {
564         this.language = lang;
565         this.editorcore.language = lang;
566         this.editorcore.updateLanguage();
567      
568     },
569     // private
570     deferFocus : function(){
571         this.focus.defer(10, this);
572     },
573
574     // doc'ed in Field
575     focus : function(){
576         this.editorcore.focus();
577         
578     },
579       
580
581     // private
582     onDestroy : function(){
583         
584         
585         
586         if(this.rendered){
587             
588             for (var i =0; i < this.toolbars.length;i++) {
589                 // fixme - ask toolbars for heights?
590                 this.toolbars[i].onDestroy();
591             }
592             
593             this.wrap.dom.innerHTML = '';
594             this.wrap.remove();
595         }
596     },
597
598     // private
599     onFirstFocus : function(){
600         //Roo.log("onFirstFocus");
601         this.editorcore.onFirstFocus();
602          for (var i =0; i < this.toolbars.length;i++) {
603             this.toolbars[i].onFirstFocus();
604         }
605         
606     },
607     
608     // private
609     syncValue : function()
610     {
611         this.editorcore.syncValue();
612     },
613     
614     pushValue : function()
615     {
616         this.editorcore.pushValue();
617     },
618     
619     setStylesheets : function(stylesheets)
620     {
621         this.editorcore.setStylesheets(stylesheets);
622     },
623     
624     removeStylesheets : function()
625     {
626         this.editorcore.removeStylesheets();
627     }
628      
629     
630     // hide stuff that is not compatible
631     /**
632      * @event blur
633      * @hide
634      */
635     /**
636      * @event change
637      * @hide
638      */
639     /**
640      * @event focus
641      * @hide
642      */
643     /**
644      * @event specialkey
645      * @hide
646      */
647     /**
648      * @cfg {String} fieldClass @hide
649      */
650     /**
651      * @cfg {String} focusClass @hide
652      */
653     /**
654      * @cfg {String} autoCreate @hide
655      */
656     /**
657      * @cfg {String} inputType @hide
658      */
659     /**
660      * @cfg {String} invalidClass @hide
661      */
662     /**
663      * @cfg {String} invalidText @hide
664      */
665     /**
666      * @cfg {String} msgFx @hide
667      */
668     /**
669      * @cfg {String} validateOnBlur @hide
670      */
671 });
672  
673