a6baf6f37e4c724e6ec1625a8b89671b858b54da
[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         this.defaultAutoCreate =  {
227             tag: "textarea",
228             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
229             autocomplete: "new-password"
230         };
231     },
232
233     /**
234      * Protected method that will not generally be called directly. It
235      * is called when the editor creates its toolbar. Override this method if you need to
236      * add custom toolbar buttons.
237      * @param {HtmlEditor} editor
238      */
239     createToolbar : function(editor){
240         Roo.log("create toolbars");
241         if (!editor.toolbars || !editor.toolbars.length) {
242             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
243         }
244         
245         for (var i =0 ; i < editor.toolbars.length;i++) {
246             editor.toolbars[i] = Roo.factory(
247                     typeof(editor.toolbars[i]) == 'string' ?
248                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
249                 Roo.form.HtmlEditor);
250             editor.toolbars[i].init(editor);
251         }
252          
253         
254     },
255     /**
256      * get the Context selected node
257      * @returns {DomElement|boolean} selected node if active or false if none
258      * 
259      */
260     getSelectedNode : function()
261     {
262         if (this.toolbars.length < 2 || !this.toolbars[1].tb) {
263             return false;
264         }
265         return this.toolbars[1].tb.selectedNode;
266     
267     },
268     // private
269     onRender : function(ct, position)
270     {
271         var _t = this;
272         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
273         
274         this.wrap = this.el.wrap({
275             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
276         });
277         
278         this.editorcore.onRender(ct, position);
279          
280         if (this.resizable) {
281             this.resizeEl = new Roo.Resizable(this.wrap, {
282                 pinned : true,
283                 wrap: true,
284                 dynamic : true,
285                 minHeight : this.height,
286                 height: this.height,
287                 handles : this.resizable,
288                 width: this.width,
289                 listeners : {
290                     resize : function(r, w, h) {
291                         _t.onResize(w,h); // -something
292                     }
293                 }
294             });
295             
296         }
297         this.createToolbar(this);
298        
299         
300         if(!this.width){
301             this.setSize(this.wrap.getSize());
302         }
303         if (this.resizeEl) {
304             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
305             // should trigger onReize..
306         }
307         
308         this.keyNav = new Roo.KeyNav(this.el, {
309             
310             "tab" : function(e){
311                 e.preventDefault();
312                 
313                 var value = this.getValue();
314                 
315                 var start = this.el.dom.selectionStart;
316                 var end = this.el.dom.selectionEnd;
317                 
318                 if(!e.shiftKey){
319                     
320                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
321                     this.el.dom.setSelectionRange(end + 1, end + 1);
322                     return;
323                 }
324                 
325                 var f = value.substring(0, start).split("\t");
326                 
327                 if(f.pop().length != 0){
328                     return;
329                 }
330                 
331                 this.setValue(f.join("\t") + value.substring(end));
332                 this.el.dom.setSelectionRange(start - 1, start - 1);
333                 
334             },
335             
336             "home" : function(e){
337                 e.preventDefault();
338                 
339                 var curr = this.el.dom.selectionStart;
340                 var lines = this.getValue().split("\n");
341                 
342                 if(!lines.length){
343                     return;
344                 }
345                 
346                 if(e.ctrlKey){
347                     this.el.dom.setSelectionRange(0, 0);
348                     return;
349                 }
350                 
351                 var pos = 0;
352                 
353                 for (var i = 0; i < lines.length;i++) {
354                     pos += lines[i].length;
355                     
356                     if(i != 0){
357                         pos += 1;
358                     }
359                     
360                     if(pos < curr){
361                         continue;
362                     }
363                     
364                     pos -= lines[i].length;
365                     
366                     break;
367                 }
368                 
369                 if(!e.shiftKey){
370                     this.el.dom.setSelectionRange(pos, pos);
371                     return;
372                 }
373                 
374                 this.el.dom.selectionStart = pos;
375                 this.el.dom.selectionEnd = curr;
376             },
377             
378             "end" : function(e){
379                 e.preventDefault();
380                 
381                 var curr = this.el.dom.selectionStart;
382                 var lines = this.getValue().split("\n");
383                 
384                 if(!lines.length){
385                     return;
386                 }
387                 
388                 if(e.ctrlKey){
389                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
390                     return;
391                 }
392                 
393                 var pos = 0;
394                 
395                 for (var i = 0; i < lines.length;i++) {
396                     
397                     pos += lines[i].length;
398                     
399                     if(i != 0){
400                         pos += 1;
401                     }
402                     
403                     if(pos < curr){
404                         continue;
405                     }
406                     
407                     break;
408                 }
409                 
410                 if(!e.shiftKey){
411                     this.el.dom.setSelectionRange(pos, pos);
412                     return;
413                 }
414                 
415                 this.el.dom.selectionStart = curr;
416                 this.el.dom.selectionEnd = pos;
417             },
418
419             scope : this,
420
421             doRelay : function(foo, bar, hname){
422                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
423             },
424
425             forceKeyDown: true
426         });
427         
428 //        if(this.autosave && this.w){
429 //            this.autoSaveFn = setInterval(this.autosave, 1000);
430 //        }
431     },
432
433     // private
434     onResize : function(w, h)
435     {
436         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
437         var ew = false;
438         var eh = false;
439         
440         if(this.el ){
441             if(typeof w == 'number'){
442                 var aw = w - this.wrap.getFrameWidth('lr');
443                 this.el.setWidth(this.adjustWidth('textarea', aw));
444                 ew = aw;
445             }
446             if(typeof h == 'number'){
447                 var tbh = 0;
448                 for (var i =0; i < this.toolbars.length;i++) {
449                     // fixme - ask toolbars for heights?
450                     tbh += this.toolbars[i].tb.el.getHeight();
451                     if (this.toolbars[i].footer) {
452                         tbh += this.toolbars[i].footer.el.getHeight();
453                     }
454                 }
455                 
456                 
457                 
458                 
459                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
460                 ah -= 5; // knock a few pixes off for look..
461 //                Roo.log(ah);
462                 this.el.setHeight(this.adjustWidth('textarea', ah));
463                 var eh = ah;
464             }
465         }
466         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
467         this.editorcore.onResize(ew,eh);
468         
469     },
470
471     /**
472      * Toggles the editor between standard and source edit mode.
473      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
474      */
475     toggleSourceEdit : function(sourceEditMode)
476     {
477         this.editorcore.toggleSourceEdit(sourceEditMode);
478         
479         if(this.editorcore.sourceEditMode){
480             Roo.log('editor - showing textarea');
481             
482 //            Roo.log('in');
483 //            Roo.log(this.syncValue());
484             this.editorcore.syncValue();
485             this.el.removeClass('x-hidden');
486             this.el.dom.removeAttribute('tabIndex');
487             this.el.focus();
488             this.el.dom.scrollTop = 0;
489             
490             
491             for (var i = 0; i < this.toolbars.length; i++) {
492                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
493                     this.toolbars[i].tb.hide();
494                     this.toolbars[i].footer.hide();
495                 }
496             }
497             
498         }else{
499             Roo.log('editor - hiding textarea');
500 //            Roo.log('out')
501 //            Roo.log(this.pushValue()); 
502             this.editorcore.pushValue();
503             
504             this.el.addClass('x-hidden');
505             this.el.dom.setAttribute('tabIndex', -1);
506             
507             for (var i = 0; i < this.toolbars.length; i++) {
508                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
509                     this.toolbars[i].tb.show();
510                     this.toolbars[i].footer.show();
511                 }
512             }
513             
514             //this.deferFocus();
515         }
516         
517         this.setSize(this.wrap.getSize());
518         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
519         
520         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
521     },
522  
523     // private (for BoxComponent)
524     adjustSize : Roo.BoxComponent.prototype.adjustSize,
525
526     // private (for BoxComponent)
527     getResizeEl : function(){
528         return this.wrap;
529     },
530
531     // private (for BoxComponent)
532     getPositionEl : function(){
533         return this.wrap;
534     },
535
536     // private
537     initEvents : function(){
538         this.originalValue = this.getValue();
539     },
540
541     /**
542      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
543      * @method
544      */
545     markInvalid : Roo.emptyFn,
546     /**
547      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
548      * @method
549      */
550     clearInvalid : Roo.emptyFn,
551
552     setValue : function(v){
553         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
554         this.editorcore.pushValue();
555     },
556
557     /**
558      * update the language in the body - really done by core
559      * @param {String} language - eg. en / ar / zh-CN etc..
560      */
561     updateLanguage : function(lang)
562     {
563         this.language = lang;
564         this.editorcore.language = lang;
565         this.editorcore.updateLanguage();
566      
567     },
568     // private
569     deferFocus : function(){
570         this.focus.defer(10, this);
571     },
572
573     // doc'ed in Field
574     focus : function(){
575         this.editorcore.focus();
576         
577     },
578       
579
580     // private
581     onDestroy : function(){
582         
583         
584         
585         if(this.rendered){
586             
587             for (var i =0; i < this.toolbars.length;i++) {
588                 // fixme - ask toolbars for heights?
589                 this.toolbars[i].onDestroy();
590             }
591             
592             this.wrap.dom.innerHTML = '';
593             this.wrap.remove();
594         }
595     },
596
597     // private
598     onFirstFocus : function(){
599         //Roo.log("onFirstFocus");
600         this.editorcore.onFirstFocus();
601          for (var i =0; i < this.toolbars.length;i++) {
602             this.toolbars[i].onFirstFocus();
603         }
604         
605     },
606     
607     // private
608     syncValue : function()
609     {
610         this.editorcore.syncValue();
611     },
612     
613     pushValue : function()
614     {
615         this.editorcore.pushValue();
616     },
617     
618     setStylesheets : function(stylesheets)
619     {
620         this.editorcore.setStylesheets(stylesheets);
621     },
622     
623     removeStylesheets : function()
624     {
625         this.editorcore.removeStylesheets();
626     }
627      
628     
629     // hide stuff that is not compatible
630     /**
631      * @event blur
632      * @hide
633      */
634     /**
635      * @event change
636      * @hide
637      */
638     /**
639      * @event focus
640      * @hide
641      */
642     /**
643      * @event specialkey
644      * @hide
645      */
646     /**
647      * @cfg {String} fieldClass @hide
648      */
649     /**
650      * @cfg {String} focusClass @hide
651      */
652     /**
653      * @cfg {String} autoCreate @hide
654      */
655     /**
656      * @cfg {String} inputType @hide
657      */
658     /**
659      * @cfg {String} invalidClass @hide
660      */
661     /**
662      * @cfg {String} invalidText @hide
663      */
664     /**
665      * @cfg {String} msgFx @hide
666      */
667     /**
668      * @cfg {String} validateOnBlur @hide
669      */
670 });
671  
672