2289ab8e9dcf994da45724fcc095bfd349d937c0
[roojs1] / Roo / form / HtmlEditor / ToolbarStandard.js
1 /*
2  * Based on
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *  
6  
7  */
8
9 /**
10  * @class Roo.form.HtmlEditor.ToolbarStandard
11  * Basic Toolbar
12  * @children   Roo.Toolbar.Item Roo.Toolbar.Button Roo.Toolbar.SplitButton Roo.form.Field 
13
14  * Usage:
15  *
16  new Roo.form.HtmlEditor({
17     ....
18     toolbars : [
19         new Roo.form.HtmlEditorToolbar1({
20             disable : { fonts: 1 , format: 1, ..., ... , ...],
21             btns : [ .... ]
22         })
23     }
24      
25  * 
26  * @cfg {Object} disable List of elements to disable..
27  * @cfg {Roo.Toolbar.Item|Roo.Toolbar.Button|Roo.Toolbar.SplitButton|Roo.form.Field} btns[] List of additional buttons.
28  * 
29  * 
30  * NEEDS Extra CSS? 
31  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
32  */
33  
34 Roo.form.HtmlEditor.ToolbarStandard = function(config)
35 {
36     
37     Roo.apply(this, config);
38     
39     // default disabled, based on 'good practice'..
40     this.disable = this.disable || {};
41     Roo.applyIf(this.disable, {
42         fontSize : true,
43         colors : true,
44         specialElements : true
45     });
46     
47     
48     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
49     // dont call parent... till later.
50 }
51
52 Roo.form.HtmlEditor.ToolbarStandard.prototype = {
53     
54     tb: false,
55     
56     rendered: false,
57     
58     editor : false,
59     editorcore : false,
60     /**
61      * @cfg {Object} disable  List of toolbar elements to disable
62          
63      */
64     disable : false,
65     
66     
67      /**
68      * @cfg {String} createLinkText The default text for the create link prompt
69      */
70     createLinkText : 'Please enter the URL for the link:',
71     /**
72      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
73      */
74     defaultLinkValue : 'http:/'+'/',
75    
76     
77       /**
78      * @cfg {Array} fontFamilies An array of available font families
79      */
80     fontFamilies : [
81         'Arial',
82         'Courier New',
83         'Tahoma',
84         'Times New Roman',
85         'Verdana'
86     ],
87     
88     specialChars : [
89            "©",
90           "®",     
91           "™",    
92           "£" ,    
93          // "—",    
94           "…",    
95           "÷" ,    
96         //  "á" ,     ?? a acute?
97            "€"    , //Euro
98        //   "“"    ,
99         //  "”"    ,
100         //  "•"    ,
101           "°"  //   , // degrees
102
103          // "é"     , // e ecute
104          // "ú"     , // u ecute?
105     ],
106     
107     specialElements : [
108         {
109             text: "Insert Table",
110             xtype: 'MenuItem',
111             xns : Roo.Menu,
112             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
113                 
114         },
115         {    
116             text: "Insert Image",
117             xtype: 'MenuItem',
118             xns : Roo.Menu,
119             ihtml : '<img src="about:blank"/>'
120             
121         }
122         
123          
124     ],
125     
126     
127     inputElements : [ 
128             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
129             "input:submit", "input:button", "select", "textarea", "label" ],
130     formats : [
131         ["p"] ,  
132         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
133         ["pre"],[ "code"], 
134         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
135         ['div'],['span'],
136         ['sup'],['sub']
137     ],
138     
139     cleanStyles : [
140         "font-size"
141     ],
142      /**
143      * @cfg {String} defaultFont default font to use.
144      */
145     defaultFont: 'tahoma',
146    
147     fontSelect : false,
148     
149     
150     formatCombo : false,
151     
152     init : function(editor)
153     {
154         this.editor = editor;
155         this.editorcore = editor.editorcore ? editor.editorcore : editor;
156         var editorcore = this.editorcore;
157         
158         var _t = this;
159         
160         var fid = editorcore.frameId;
161         var etb = this;
162         function btn(id, toggle, handler){
163             var xid = fid + '-'+ id ;
164             return {
165                 id : xid,
166                 cmd : id,
167                 cls : 'x-btn-icon x-edit-'+id,
168                 enableToggle:toggle !== false,
169                 scope: _t, // was editor...
170                 handler:handler||_t.relayBtnCmd,
171                 clickEvent:'mousedown',
172                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
173                 tabIndex:-1
174             };
175         }
176         
177         
178         
179         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
180         this.tb = tb;
181          // stop form submits
182         tb.el.on('click', function(e){
183             e.preventDefault(); // what does this do?
184         });
185
186         if(!this.disable.font) { // && !Roo.isSafari){
187             /* why no safari for fonts 
188             editor.fontSelect = tb.el.createChild({
189                 tag:'select',
190                 tabIndex: -1,
191                 cls:'x-font-select',
192                 html: this.createFontOptions()
193             });
194             
195             editor.fontSelect.on('change', function(){
196                 var font = editor.fontSelect.dom.value;
197                 editor.relayCmd('fontname', font);
198                 editor.deferFocus();
199             }, editor);
200             
201             tb.add(
202                 editor.fontSelect.dom,
203                 '-'
204             );
205             */
206             
207         };
208         if(!this.disable.formats){
209             this.formatCombo = new Roo.form.ComboBox({
210                 store: new Roo.data.SimpleStore({
211                     id : 'tag',
212                     fields: ['tag'],
213                     data : this.formats // from states.js
214                 }),
215                 blockFocus : true,
216                 name : '',
217                 //autoCreate : {tag: "div",  size: "20"},
218                 displayField:'tag',
219                 typeAhead: false,
220                 mode: 'local',
221                 editable : false,
222                 triggerAction: 'all',
223                 emptyText:'Add tag',
224                 selectOnFocus:true,
225                 width:135,
226                 listeners : {
227                     'select': function(c, r, i) {
228                         editorcore.insertTag(r.get('tag'));
229                         editor.focus();
230                     }
231                 }
232
233             });
234             tb.addField(this.formatCombo);
235             
236         }
237         
238         if(!this.disable.format){
239             tb.add(
240                 btn('bold'),
241                 btn('italic'),
242                 btn('underline'),
243                 btn('strikethrough')
244             );
245         };
246         if(!this.disable.fontSize){
247             tb.add(
248                 '-',
249                 
250                 
251                 btn('increasefontsize', false, editorcore.adjustFont),
252                 btn('decreasefontsize', false, editorcore.adjustFont)
253             );
254         };
255         
256         
257         if(!this.disable.colors){
258             tb.add(
259                 '-', {
260                     id:editorcore.frameId +'-forecolor',
261                     cls:'x-btn-icon x-edit-forecolor',
262                     clickEvent:'mousedown',
263                     tooltip: this.buttonTips['forecolor'] || undefined,
264                     tabIndex:-1,
265                     menu : new Roo.menu.ColorMenu({
266                         allowReselect: true,
267                         focus: Roo.emptyFn,
268                         value:'000000',
269                         plain:true,
270                         selectHandler: function(cp, color){
271                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
272                             editor.deferFocus();
273                         },
274                         scope: editorcore,
275                         clickEvent:'mousedown'
276                     })
277                 }, {
278                     id:editorcore.frameId +'backcolor',
279                     cls:'x-btn-icon x-edit-backcolor',
280                     clickEvent:'mousedown',
281                     tooltip: this.buttonTips['backcolor'] || undefined,
282                     tabIndex:-1,
283                     menu : new Roo.menu.ColorMenu({
284                         focus: Roo.emptyFn,
285                         value:'FFFFFF',
286                         plain:true,
287                         allowReselect: true,
288                         selectHandler: function(cp, color){
289                             if(Roo.isGecko){
290                                 editorcore.execCmd('useCSS', false);
291                                 editorcore.execCmd('hilitecolor', color);
292                                 editorcore.execCmd('useCSS', true);
293                                 editor.deferFocus();
294                             }else{
295                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
296                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
297                                 editor.deferFocus();
298                             }
299                         },
300                         scope:editorcore,
301                         clickEvent:'mousedown'
302                     })
303                 }
304             );
305         };
306         // now add all the items...
307         
308
309         if(!this.disable.alignments){
310             tb.add(
311                 '-',
312                 btn('justifyleft'),
313                 btn('justifycenter'),
314                 btn('justifyright')
315             );
316         };
317
318         //if(!Roo.isSafari){
319             if(!this.disable.links){
320                 tb.add(
321                     '-',
322                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
323                 );
324             };
325
326             if(!this.disable.lists){
327                 tb.add(
328                     '-',
329                     btn('insertorderedlist'),
330                     btn('insertunorderedlist')
331                 );
332             }
333             if(!this.disable.sourceEdit){
334                 tb.add(
335                     '-',
336                     btn('sourceedit', true, function(btn){
337                         this.toggleSourceEdit(btn.pressed);
338                     })
339                 );
340             }
341         //}
342         
343         var smenu = { };
344         // special menu.. - needs to be tidied up..
345         if (!this.disable.special) {
346             smenu = {
347                 text: "&#169;",
348                 cls: 'x-edit-none',
349                 
350                 menu : {
351                     items : []
352                 }
353             };
354             for (var i =0; i < this.specialChars.length; i++) {
355                 smenu.menu.items.push({
356                     
357                     html: this.specialChars[i],
358                     handler: function(a,b) {
359                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
360                         //editor.insertAtCursor(a.html);
361                         
362                     },
363                     tabIndex:-1
364                 });
365             }
366             
367             
368             tb.add(smenu);
369             
370             
371         }
372         
373         var cmenu = { };
374         if (!this.disable.cleanStyles) {
375             cmenu = {
376                 cls: 'x-btn-icon x-btn-clear',
377                 
378                 menu : {
379                     items : []
380                 }
381             };
382             for (var i =0; i < this.cleanStyles.length; i++) {
383                 cmenu.menu.items.push({
384                     actiontype : this.cleanStyles[i],
385                     html: 'Remove ' + this.cleanStyles[i],
386                     handler: function(a,b) {
387 //                        Roo.log(a);
388 //                        Roo.log(b);
389                         var c = Roo.get(editorcore.doc.body);
390                         c.select('[style]').each(function(s) {
391                             s.dom.style.removeProperty(a.actiontype);
392                         });
393                         editorcore.syncValue();
394                     },
395                     tabIndex:-1
396                 });
397             }
398             cmenu.menu.items.push({
399                 actiontype : 'tablewidths',
400                 html: 'Remove Table Widths',
401                 handler: function(a,b) {
402                     editorcore.cleanTableWidths();
403                     editorcore.syncValue();
404                 },
405                 tabIndex:-1
406             });
407             cmenu.menu.items.push({
408                 actiontype : 'word',
409                 html: 'Remove MS Word Formating',
410                 handler: function(a,b) {
411                     editorcore.cleanWord();
412                     editorcore.syncValue();
413                 },
414                 tabIndex:-1
415             });
416             
417             cmenu.menu.items.push({
418                 actiontype : 'all',
419                 html: 'Remove All Styles',
420                 handler: function(a,b) {
421                     
422                     var c = Roo.get(editorcore.doc.body);
423                     c.select('[style]').each(function(s) {
424                         s.dom.removeAttribute('style');
425                     });
426                     editorcore.syncValue();
427                 },
428                 tabIndex:-1
429             });
430             
431             cmenu.menu.items.push({
432                 actiontype : 'all',
433                 html: 'Remove All CSS Classes',
434                 handler: function(a,b) {
435                     
436                     var c = Roo.get(editorcore.doc.body);
437                     c.select('[class]').each(function(s) {
438                         s.dom.removeAttribute('class');
439                     });
440                     editorcore.cleanWord();
441                     editorcore.syncValue();
442                 },
443                 tabIndex:-1
444             });
445             
446              cmenu.menu.items.push({
447                 actiontype : 'tidy',
448                 html: 'Tidy HTML Source',
449                 handler: function(a,b) {
450                     new Roo.htmleditor.Tidy(editorcore.doc.body);
451                     editorcore.syncValue();
452                 },
453                 tabIndex:-1
454             });
455             
456             
457             tb.add(cmenu);
458         }
459          
460         if (!this.disable.specialElements) {
461             var semenu = {
462                 text: "Other;",
463                 cls: 'x-edit-none',
464                 menu : {
465                     items : []
466                 }
467             };
468             for (var i =0; i < this.specialElements.length; i++) {
469                 semenu.menu.items.push(
470                     Roo.apply({ 
471                         handler: function(a,b) {
472                             editor.insertAtCursor(this.ihtml);
473                         }
474                     }, this.specialElements[i])
475                 );
476                     
477             }
478             
479             tb.add(semenu);
480             
481             
482         }
483          
484         
485         if (this.btns) {
486             for(var i =0; i< this.btns.length;i++) {
487                 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
488                 b.cls =  'x-edit-none';
489                 
490                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
491                     b.cls += ' x-init-enable';
492                 }
493                 
494                 b.scope = editorcore;
495                 tb.add(b);
496             }
497         
498         }
499         
500         
501         
502         // disable everything...
503         
504         this.tb.items.each(function(item){
505             
506            if(
507                 item.id != editorcore.frameId+ '-sourceedit' && 
508                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
509             ){
510                 
511                 item.disable();
512             }
513         });
514         this.rendered = true;
515         
516         // the all the btns;
517         editor.on('editorevent', this.updateToolbar, this);
518         // other toolbars need to implement this..
519         //editor.on('editmodechange', this.updateToolbar, this);
520     },
521     
522     
523     relayBtnCmd : function(btn) {
524         this.editorcore.relayCmd(btn.cmd);
525     },
526     // private used internally
527     createLink : function(){
528         //Roo.log("create link?");
529         var ec = this.editorcore;
530         Roo.MessageBox.prompt("Add Link URL",this.createLinkText, function(btn, url) {
531             if (btn != 'ok') {
532                 return;
533             }
534             if(url && url != 'http:/'+'/'){
535                 ec.relayCmd('createlink', url);
536             }
537         });
538         
539     },
540
541     
542     /**
543      * Protected method that will not generally be called directly. It triggers
544      * a toolbar update by reading the markup state of the current selection in the editor.
545      */
546     updateToolbar: function(){
547
548         if(!this.editorcore.activated){
549             this.editor.onFirstFocus();
550             return;
551         }
552
553         var btns = this.tb.items.map, 
554             doc = this.editorcore.doc,
555             frameId = this.editorcore.frameId;
556
557         if(!this.disable.font && !Roo.isSafari){
558             /*
559             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
560             if(name != this.fontSelect.dom.value){
561                 this.fontSelect.dom.value = name;
562             }
563             */
564         }
565         if(!this.disable.format){
566             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
567             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
568             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
569             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
570         }
571         if(!this.disable.alignments){
572             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
573             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
574             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
575         }
576         if(!Roo.isSafari && !this.disable.lists){
577             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
578             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
579         }
580         
581         var ans = this.editorcore.getAllAncestors();
582         if (this.formatCombo) {
583             
584             
585             var store = this.formatCombo.store;
586             this.formatCombo.setValue("");
587             for (var i =0; i < ans.length;i++) {
588                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
589                     // select it..
590                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
591                     break;
592                 }
593             }
594         }
595         
596         
597         
598         // hides menus... - so this cant be on a menu...
599         Roo.menu.MenuMgr.hideAll();
600
601         //this.editorsyncValue();
602     },
603    
604     
605     createFontOptions : function(){
606         var buf = [], fs = this.fontFamilies, ff, lc;
607         
608         
609         
610         for(var i = 0, len = fs.length; i< len; i++){
611             ff = fs[i];
612             lc = ff.toLowerCase();
613             buf.push(
614                 '<option value="',lc,'" style="font-family:',ff,';"',
615                     (this.defaultFont == lc ? ' selected="true">' : '>'),
616                     ff,
617                 '</option>'
618             );
619         }
620         return buf.join('');
621     },
622     
623     toggleSourceEdit : function(sourceEditMode){
624         
625         Roo.log("toolbar toogle");
626         if(sourceEditMode === undefined){
627             sourceEditMode = !this.sourceEditMode;
628         }
629         this.sourceEditMode = sourceEditMode === true;
630         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
631         // just toggle the button?
632         if(btn.pressed !== this.sourceEditMode){
633             btn.toggle(this.sourceEditMode);
634             return;
635         }
636         
637         if(sourceEditMode){
638             Roo.log("disabling buttons");
639             this.tb.items.each(function(item){
640                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
641                     item.disable();
642                 }
643             });
644           
645         }else{
646             Roo.log("enabling buttons");
647             if(this.editorcore.initialized){
648                 this.tb.items.each(function(item){
649                     item.enable();
650                 });
651                 // initialize 'blocks'
652                 Roo.each(Roo.get(this.editorcore.doc.body).query('*[data-block]'), function(e) {
653                     Roo.htmleditor.Block.factory(e).updateElement(e);
654                 },this);
655             
656             }
657             
658         }
659         Roo.log("calling toggole on editor");
660         // tell the editor that it's been pressed..
661         this.editor.toggleSourceEdit(sourceEditMode);
662        
663     },
664      /**
665      * Object collection of toolbar tooltips for the buttons in the editor. The key
666      * is the command id associated with that button and the value is a valid QuickTips object.
667      * For example:
668 <pre><code>
669 {
670     bold : {
671         title: 'Bold (Ctrl+B)',
672         text: 'Make the selected text bold.',
673         cls: 'x-html-editor-tip'
674     },
675     italic : {
676         title: 'Italic (Ctrl+I)',
677         text: 'Make the selected text italic.',
678         cls: 'x-html-editor-tip'
679     },
680     ...
681 </code></pre>
682     * @type Object
683      */
684     buttonTips : {
685         bold : {
686             title: 'Bold (Ctrl+B)',
687             text: 'Make the selected text bold.',
688             cls: 'x-html-editor-tip'
689         },
690         italic : {
691             title: 'Italic (Ctrl+I)',
692             text: 'Make the selected text italic.',
693             cls: 'x-html-editor-tip'
694         },
695         underline : {
696             title: 'Underline (Ctrl+U)',
697             text: 'Underline the selected text.',
698             cls: 'x-html-editor-tip'
699         },
700         strikethrough : {
701             title: 'Strikethrough',
702             text: 'Strikethrough the selected text.',
703             cls: 'x-html-editor-tip'
704         },
705         increasefontsize : {
706             title: 'Grow Text',
707             text: 'Increase the font size.',
708             cls: 'x-html-editor-tip'
709         },
710         decreasefontsize : {
711             title: 'Shrink Text',
712             text: 'Decrease the font size.',
713             cls: 'x-html-editor-tip'
714         },
715         backcolor : {
716             title: 'Text Highlight Color',
717             text: 'Change the background color of the selected text.',
718             cls: 'x-html-editor-tip'
719         },
720         forecolor : {
721             title: 'Font Color',
722             text: 'Change the color of the selected text.',
723             cls: 'x-html-editor-tip'
724         },
725         justifyleft : {
726             title: 'Align Text Left',
727             text: 'Align text to the left.',
728             cls: 'x-html-editor-tip'
729         },
730         justifycenter : {
731             title: 'Center Text',
732             text: 'Center text in the editor.',
733             cls: 'x-html-editor-tip'
734         },
735         justifyright : {
736             title: 'Align Text Right',
737             text: 'Align text to the right.',
738             cls: 'x-html-editor-tip'
739         },
740         insertunorderedlist : {
741             title: 'Bullet List',
742             text: 'Start a bulleted list.',
743             cls: 'x-html-editor-tip'
744         },
745         insertorderedlist : {
746             title: 'Numbered List',
747             text: 'Start a numbered list.',
748             cls: 'x-html-editor-tip'
749         },
750         createlink : {
751             title: 'Hyperlink',
752             text: 'Make the selected text a hyperlink.',
753             cls: 'x-html-editor-tip'
754         },
755         sourceedit : {
756             title: 'Source Edit',
757             text: 'Switch to source editing mode.',
758             cls: 'x-html-editor-tip'
759         }
760     },
761     // private
762     onDestroy : function(){
763         if(this.rendered){
764             
765             this.tb.items.each(function(item){
766                 if(item.menu){
767                     item.menu.removeAll();
768                     if(item.menu.el){
769                         item.menu.el.destroy();
770                     }
771                 }
772                 item.destroy();
773             });
774              
775         }
776     },
777     onFirstFocus: function() {
778         this.tb.items.each(function(item){
779            item.enable();
780         });
781     }
782 };
783
784
785
786