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