Roo/form/HtmlEditor.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.
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     // id of frame..
91     frameId: false,
92     
93     // private properties
94     validationEvent : false,
95     deferHeight: true,
96     initialized : false,
97     activated : false,
98     
99     onFocus : Roo.emptyFn,
100     iframePad:3,
101     hideMode:'offsets',
102     
103     actionMode : 'container', // defaults to hiding it...
104     
105     defaultAutoCreate : { // modified by initCompnoent..
106         tag: "textarea",
107         style:"width:500px;height:300px;",
108         autocomplete: "off"
109     },
110
111     // private
112     initComponent : function(){
113         this.addEvents({
114             /**
115              * @event initialize
116              * Fires when the editor is fully initialized (including the iframe)
117              * @param {HtmlEditor} this
118              */
119             initialize: true,
120             /**
121              * @event activate
122              * Fires when the editor is first receives the focus. Any insertion must wait
123              * until after this event.
124              * @param {HtmlEditor} this
125              */
126             activate: true,
127              /**
128              * @event beforesync
129              * Fires before the textarea is updated with content from the editor iframe. Return false
130              * to cancel the sync.
131              * @param {HtmlEditor} this
132              * @param {String} html
133              */
134             beforesync: true,
135              /**
136              * @event beforepush
137              * Fires before the iframe editor is updated with content from the textarea. Return false
138              * to cancel the push.
139              * @param {HtmlEditor} this
140              * @param {String} html
141              */
142             beforepush: true,
143              /**
144              * @event sync
145              * Fires when the textarea is updated with content from the editor iframe.
146              * @param {HtmlEditor} this
147              * @param {String} html
148              */
149             sync: true,
150              /**
151              * @event push
152              * Fires when the iframe editor is updated with content from the textarea.
153              * @param {HtmlEditor} this
154              * @param {String} html
155              */
156             push: true,
157              /**
158              * @event editmodechange
159              * Fires when the editor switches edit modes
160              * @param {HtmlEditor} this
161              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
162              */
163             editmodechange: true,
164             /**
165              * @event editorevent
166              * Fires when on any editor (mouse up/down cursor movement etc.) - used for toolbar hooks.
167              * @param {HtmlEditor} this
168              */
169             editorevent: true,
170             /**
171              * @event firstfocus
172              * Fires when on first focus - needed by toolbars..
173              * @param {HtmlEditor} this
174              */
175             firstfocus: true,
176             /**
177              * @event autosave
178              * Auto save the htmlEditor value as a file into Events
179              * @param {HtmlEditor} this
180              */
181             autosave: true,
182             /**
183              * @event savedpreview
184              * preview the saved version of htmlEditor
185              * @param {HtmlEditor} this
186              */
187             savedpreview: true
188         });
189         this.defaultAutoCreate =  {
190             tag: "textarea",
191             style:'width: ' + this.width + 'px;height: ' + this.height + 'px;',
192             autocomplete: "off"
193         };
194     },
195
196     /**
197      * Protected method that will not generally be called directly. It
198      * is called when the editor creates its toolbar. Override this method if you need to
199      * add custom toolbar buttons.
200      * @param {HtmlEditor} editor
201      */
202     createToolbar : function(editor){
203         Roo.log("create toolbars");
204         if (!editor.toolbars || !editor.toolbars.length) {
205             editor.toolbars = [ new Roo.form.HtmlEditor.ToolbarStandard() ]; // can be empty?
206         }
207         
208         for (var i =0 ; i < editor.toolbars.length;i++) {
209             editor.toolbars[i] = Roo.factory(
210                     typeof(editor.toolbars[i]) == 'string' ?
211                         { xtype: editor.toolbars[i]} : editor.toolbars[i],
212                 Roo.form.HtmlEditor);
213             editor.toolbars[i].init(editor);
214         }
215          
216         
217     },
218
219      
220     // private
221     onRender : function(ct, position)
222     {
223         var _t = this;
224         Roo.form.HtmlEditor.superclass.onRender.call(this, ct, position);
225         
226         this.wrap = this.el.wrap({
227             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
228         });
229         
230         this.editorcore.onRender(ct, position);
231          
232         if (this.resizable) {
233             this.resizeEl = new Roo.Resizable(this.wrap, {
234                 pinned : true,
235                 wrap: true,
236                 dynamic : true,
237                 minHeight : this.height,
238                 height: this.height,
239                 handles : this.resizable,
240                 width: this.width,
241                 listeners : {
242                     resize : function(r, w, h) {
243                         _t.onResize(w,h); // -something
244                     }
245                 }
246             });
247             
248         }
249         this.createToolbar(this);
250        
251         
252         if(!this.width){
253             this.setSize(this.wrap.getSize());
254         }
255         if (this.resizeEl) {
256             this.resizeEl.resizeTo.defer(100, this.resizeEl,[ this.width,this.height ] );
257             // should trigger onReize..
258         }
259         
260         this.keyNav = new Roo.KeyNav(this.el, {
261             
262             "tab" : function(e){
263                 e.preventDefault();
264                 
265                 var value = this.getValue();
266                 
267                 var start = this.el.dom.selectionStart;
268                 var end = this.el.dom.selectionEnd;
269                 
270                 if(!e.shiftKey){
271                     
272                     this.setValue(value.substring(0, start) + "\t" + value.substring(end));
273                     this.el.dom.setSelectionRange(end + 1, end + 1);
274                     return;
275                 }
276                 
277                 var f = value.substring(0, start).split("\t");
278                 
279                 if(f.pop().length != 0){
280                     return;
281                 }
282                 
283                 this.setValue(f.join("\t") + value.substring(end));
284                 this.el.dom.setSelectionRange(start - 1, start - 1);
285                 
286             },
287             
288             "home" : function(e){
289                 e.preventDefault();
290                 
291                 var curr = this.el.dom.selectionStart;
292                 var lines = this.getValue().split("\n");
293                 
294                 if(!lines.length){
295                     return;
296                 }
297                 
298                 if(e.ctrlKey){
299                     this.el.dom.setSelectionRange(0, 0);
300                     return;
301                 }
302                 
303                 var pos = 0;
304                 
305                 for (var i = 0; i < lines.length;i++) {
306                     pos += lines[i].length;
307                     
308                     if(i != 0){
309                         pos += 1;
310                     }
311                     
312                     if(pos < curr){
313                         continue;
314                     }
315                     
316                     pos -= lines[i].length;
317                     
318                     break;
319                 }
320                 
321                 if(!e.shiftKey){
322                     this.el.dom.setSelectionRange(pos, pos);
323                     return;
324                 }
325                 
326                 //var selection = window.getSelection();
327                 var range = document.createRange();
328                 range.selectNodeContents(text);
329                 range.collapse(true);
330                 range.moveEnd('character', pos);
331                 range.moveStart('character', pos);
332                 range.select();
333             },
334             
335             "end" : function(e){
336                 e.preventDefault();
337                 
338                 var curr = this.el.dom.selectionStart;
339                 var lines = this.getValue().split("\n");
340                 
341                 if(!lines.length){
342                     return;
343                 }
344                 
345                 if(e.ctrlKey){
346                     this.el.dom.setSelectionRange(this.getValue().length, this.getValue().length);
347                     return;
348                 }
349                 
350                 var pos = 0;
351                 
352                 for (var i = 0; i < lines.length;i++) {
353                     
354                     pos += lines[i].length;
355                     
356                     if(i != 0){
357                         pos += 1;
358                     }
359                     
360                     if(pos < curr){
361                         continue;
362                     }
363                     
364                     break;
365                 }
366                 
367                 this.el.dom.setSelectionRange(pos, pos);
368             },
369
370             scope : this,
371
372             doRelay : function(foo, bar, hname){
373                 return Roo.KeyNav.prototype.doRelay.apply(this, arguments);
374             },
375
376             forceKeyDown: true
377         });
378         
379 //        if(this.autosave && this.w){
380 //            this.autoSaveFn = setInterval(this.autosave, 1000);
381 //        }
382     },
383
384     // private
385     onResize : function(w, h)
386     {
387         Roo.form.HtmlEditor.superclass.onResize.apply(this, arguments);
388         var ew = false;
389         var eh = false;
390         
391         if(this.el ){
392             if(typeof w == 'number'){
393                 var aw = w - this.wrap.getFrameWidth('lr');
394                 this.el.setWidth(this.adjustWidth('textarea', aw));
395                 ew = aw;
396             }
397             if(typeof h == 'number'){
398                 var tbh = 0;
399                 for (var i =0; i < this.toolbars.length;i++) {
400                     // fixme - ask toolbars for heights?
401                     tbh += this.toolbars[i].tb.el.getHeight();
402                     if (this.toolbars[i].footer) {
403                         tbh += this.toolbars[i].footer.el.getHeight();
404                     }
405                 }
406                 
407                 
408                 
409                 
410                 var ah = h - this.wrap.getFrameWidth('tb') - tbh;// this.tb.el.getHeight();
411                 ah -= 5; // knock a few pixes off for look..
412                 Roo.log(ah);
413                 this.el.setHeight(this.adjustWidth('textarea', ah));
414                 var eh = ah;
415             }
416         }
417         Roo.log('onResize:' + [w,h,ew,eh].join(',') );
418         this.editorcore.onResize(ew,eh);
419         
420     },
421
422     /**
423      * Toggles the editor between standard and source edit mode.
424      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
425      */
426     toggleSourceEdit : function(sourceEditMode)
427     {
428         this.editorcore.toggleSourceEdit(sourceEditMode);
429         
430         if(this.editorcore.sourceEditMode){
431             Roo.log('editor - showing textarea');
432             
433 //            Roo.log('in');
434 //            Roo.log(this.syncValue());
435             this.editorcore.syncValue();
436             this.el.removeClass('x-hidden');
437             this.el.dom.removeAttribute('tabIndex');
438             this.el.focus();
439             
440             for (var i = 0; i < this.toolbars.length; i++) {
441                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
442                     this.toolbars[i].tb.hide();
443                     this.toolbars[i].footer.hide();
444                 }
445             }
446             
447         }else{
448             Roo.log('editor - hiding textarea');
449 //            Roo.log('out')
450 //            Roo.log(this.pushValue()); 
451             this.editorcore.pushValue();
452             
453             this.el.addClass('x-hidden');
454             this.el.dom.setAttribute('tabIndex', -1);
455             
456             for (var i = 0; i < this.toolbars.length; i++) {
457                 if(this.toolbars[i] instanceof Roo.form.HtmlEditor.ToolbarContext){
458                     this.toolbars[i].tb.show();
459                     this.toolbars[i].footer.show();
460                 }
461             }
462             
463             //this.deferFocus();
464         }
465         
466         this.setSize(this.wrap.getSize());
467         this.onResize(this.wrap.getSize().width, this.wrap.getSize().height);
468         
469         this.fireEvent('editmodechange', this, this.editorcore.sourceEditMode);
470     },
471  
472     // private (for BoxComponent)
473     adjustSize : Roo.BoxComponent.prototype.adjustSize,
474
475     // private (for BoxComponent)
476     getResizeEl : function(){
477         return this.wrap;
478     },
479
480     // private (for BoxComponent)
481     getPositionEl : function(){
482         return this.wrap;
483     },
484
485     // private
486     initEvents : function(){
487         this.originalValue = this.getValue();
488     },
489
490     /**
491      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
492      * @method
493      */
494     markInvalid : Roo.emptyFn,
495     /**
496      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
497      * @method
498      */
499     clearInvalid : Roo.emptyFn,
500
501     setValue : function(v){
502         Roo.form.HtmlEditor.superclass.setValue.call(this, v);
503         this.editorcore.pushValue();
504     },
505
506      
507     // private
508     deferFocus : function(){
509         this.focus.defer(10, this);
510     },
511
512     // doc'ed in Field
513     focus : function(){
514         this.editorcore.focus();
515         
516     },
517       
518
519     // private
520     onDestroy : function(){
521         
522         
523         
524         if(this.rendered){
525             
526             for (var i =0; i < this.toolbars.length;i++) {
527                 // fixme - ask toolbars for heights?
528                 this.toolbars[i].onDestroy();
529             }
530             
531             this.wrap.dom.innerHTML = '';
532             this.wrap.remove();
533         }
534     },
535
536     // private
537     onFirstFocus : function(){
538         //Roo.log("onFirstFocus");
539         this.editorcore.onFirstFocus();
540          for (var i =0; i < this.toolbars.length;i++) {
541             this.toolbars[i].onFirstFocus();
542         }
543         
544     },
545     
546     // private
547     syncValue : function()
548     {
549         this.editorcore.syncValue();
550     },
551     
552     pushValue : function()
553     {
554         this.editorcore.pushValue();
555     }
556      
557     
558     // hide stuff that is not compatible
559     /**
560      * @event blur
561      * @hide
562      */
563     /**
564      * @event change
565      * @hide
566      */
567     /**
568      * @event focus
569      * @hide
570      */
571     /**
572      * @event specialkey
573      * @hide
574      */
575     /**
576      * @cfg {String} fieldClass @hide
577      */
578     /**
579      * @cfg {String} focusClass @hide
580      */
581     /**
582      * @cfg {String} autoCreate @hide
583      */
584     /**
585      * @cfg {String} inputType @hide
586      */
587     /**
588      * @cfg {String} invalidClass @hide
589      */
590     /**
591      * @cfg {String} invalidText @hide
592      */
593     /**
594      * @cfg {String} msgFx @hide
595      */
596     /**
597      * @cfg {String} validateOnBlur @hide
598      */
599 });
600  
601