roojs-ui.js
[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     
115     // id of frame..
116     frameId: false,
117     
118     // private properties
119     validationEvent : false,
120     deferHeight: true,
121     initialized : false,
122     activated : false,
123     
124     onFocus : Roo.emptyFn,
125     iframePad:3,
126     hideMode:'offsets',
127     
128     actionMode : 'container', // defaults to hiding it...
129     
130     defaultAutoCreate : { // modified by initCompnoent..
131         tag: "textarea",
132         style:"width:500px;height:300px;",
133         autocomplete: "new-password"
134     },
135
136     // private
137     initComponent : function(){
138         this.addEvents({
139             /**
140              * @event initialize
141              * Fires when the editor is fully initialized (including the iframe)
142              * @param {HtmlEditor} this
143              */
144             initialize: true,
145             /**
146              * @event activate
147              * Fires when the editor is first receives the focus. Any insertion must wait
148              * until after this event.
149              * @param {HtmlEditor} this
150              */
151             activate: true,
152              /**
153              * @event beforesync
154              * Fires before the textarea is updated with content from the editor iframe. Return false
155              * to cancel the sync.
156              * @param {HtmlEditor} this
157              * @param {String} html
158              */
159             beforesync: true,
160              /**
161              * @event beforepush
162              * Fires before the iframe editor is updated with content from the textarea. Return false
163              * to cancel the push.
164              * @param {HtmlEditor} this
165              * @param {String} html
166              */
167             beforepush: true,
168              /**
169              * @event sync
170              * Fires when the textarea is updated with content from the editor iframe.
171              * @param {HtmlEditor} this
172              * @param {String} html
173              */
174             sync: true,
175              /**
176              * @event push
177              * Fires when the iframe editor is updated with content from the textarea.
178              * @param {HtmlEditor} this
179              * @param {String} html
180              */
181             push: true,
182              /**
183              * @event editmodechange
184              * Fires when the editor switches edit modes
185              * @param {HtmlEditor} this
186              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
187              */
188             editmodechange: true,
189             /**
190              * @event editorevent
191              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
192              * @param {HtmlEditor} this
193              */
194             editorevent: true,
195             /**
196              * @event firstfocus
197              * Fires when on first focus - needed by toolbars..
198              * @param {HtmlEditor} this
199              */
200             firstfocus: true,
201             /**
202              * @event autosave
203              * Auto save the htmlEditor value as a file into Events
204              * @param {HtmlEditor} this
205              */
206             autosave: true,
207             /**
208              * @event savedpreview
209              * preview the saved version of htmlEditor
210              * @param {HtmlEditor} this
211              */
212             savedpreview: true,
213             
214             /**
215             * @event stylesheetsclick
216             * Fires when press the Sytlesheets button
217             * @param {Roo.HtmlEditorCore} this
218             */
219             stylesheetsclick: true,
220             /**
221             * @event paste
222             * Fires when press user pastes into the editor
223             * @param {Roo.HtmlEditorCore} this
224             */
225             paste: true 
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     // private
560     deferFocus : function(){
561         this.focus.defer(10, this);
562     },
563
564     // doc'ed in Field
565     focus : function(){
566         this.editorcore.focus();
567         
568     },
569       
570
571     // private
572     onDestroy : function(){
573         
574         
575         
576         if(this.rendered){
577             
578             for (var i =0; i < this.toolbars.length;i++) {
579                 // fixme - ask toolbars for heights?
580                 this.toolbars[i].onDestroy();
581             }
582             
583             this.wrap.dom.innerHTML = '';
584             this.wrap.remove();
585         }
586     },
587
588     // private
589     onFirstFocus : function(){
590         //Roo.log("onFirstFocus");
591         this.editorcore.onFirstFocus();
592          for (var i =0; i < this.toolbars.length;i++) {
593             this.toolbars[i].onFirstFocus();
594         }
595         
596     },
597     
598     // private
599     syncValue : function()
600     {
601         this.editorcore.syncValue();
602     },
603     
604     pushValue : function()
605     {
606         this.editorcore.pushValue();
607     },
608     
609     setStylesheets : function(stylesheets)
610     {
611         this.editorcore.setStylesheets(stylesheets);
612     },
613     
614     removeStylesheets : function()
615     {
616         this.editorcore.removeStylesheets();
617     }
618      
619     
620     // hide stuff that is not compatible
621     /**
622      * @event blur
623      * @hide
624      */
625     /**
626      * @event change
627      * @hide
628      */
629     /**
630      * @event focus
631      * @hide
632      */
633     /**
634      * @event specialkey
635      * @hide
636      */
637     /**
638      * @cfg {String} fieldClass @hide
639      */
640     /**
641      * @cfg {String} focusClass @hide
642      */
643     /**
644      * @cfg {String} autoCreate @hide
645      */
646     /**
647      * @cfg {String} inputType @hide
648      */
649     /**
650      * @cfg {String} invalidClass @hide
651      */
652     /**
653      * @cfg {String} invalidText @hide
654      */
655     /**
656      * @cfg {String} msgFx @hide
657      */
658     /**
659      * @cfg {String} validateOnBlur @hide
660      */
661 });
662  
663