Fix #6141 - super script and subscribe
[roojs1] / Roo / form / HtmlEditor / ToolbarStandard.js
1 // <script type="text/javascript">
2 /*
3  * Based on
4  * Ext JS Library 1.1.1
5  * Copyright(c) 2006-2007, Ext JS, LLC.
6  *  
7  
8  */
9
10 /**
11  * @class Roo.form.HtmlEditorToolbar1
12  * Basic Toolbar
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 {Array} 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.apply(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            "&#169;",
90           "&#174;",     
91           "&#8482;",    
92           "&#163;" ,    
93          // "&#8212;",    
94           "&#8230;",    
95           "&#247;" ,    
96         //  "&#225;" ,     ?? a acute?
97            "&#8364;"    , //Euro
98        //   "&#8220;"    ,
99         //  "&#8221;"    ,
100         //  "&#8226;"    ,
101           "&#176;"  //   , // degrees
102
103          // "&#233;"     , // e ecute
104          // "&#250;"     , // 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                     editorcore.doc.body.innerHTML = editorcore.domToHTML();
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],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 url = prompt(this.createLinkText, this.defaultLinkValue);
530         if(url && url != 'http:/'+'/'){
531             this.editorcore.relayCmd('createlink', url);
532         }
533     },
534
535     
536     /**
537      * Protected method that will not generally be called directly. It triggers
538      * a toolbar update by reading the markup state of the current selection in the editor.
539      */
540     updateToolbar: function(){
541
542         if(!this.editorcore.activated){
543             this.editor.onFirstFocus();
544             return;
545         }
546
547         var btns = this.tb.items.map, 
548             doc = this.editorcore.doc,
549             frameId = this.editorcore.frameId;
550
551         if(!this.disable.font && !Roo.isSafari){
552             /*
553             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
554             if(name != this.fontSelect.dom.value){
555                 this.fontSelect.dom.value = name;
556             }
557             */
558         }
559         if(!this.disable.format){
560             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
561             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
562             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
563             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
564         }
565         if(!this.disable.alignments){
566             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
567             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
568             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
569         }
570         if(!Roo.isSafari && !this.disable.lists){
571             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
572             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
573         }
574         
575         var ans = this.editorcore.getAllAncestors();
576         if (this.formatCombo) {
577             
578             
579             var store = this.formatCombo.store;
580             this.formatCombo.setValue("");
581             for (var i =0; i < ans.length;i++) {
582                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
583                     // select it..
584                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
585                     break;
586                 }
587             }
588         }
589         
590         
591         
592         // hides menus... - so this cant be on a menu...
593         Roo.menu.MenuMgr.hideAll();
594
595         //this.editorsyncValue();
596     },
597    
598     
599     createFontOptions : function(){
600         var buf = [], fs = this.fontFamilies, ff, lc;
601         
602         
603         
604         for(var i = 0, len = fs.length; i< len; i++){
605             ff = fs[i];
606             lc = ff.toLowerCase();
607             buf.push(
608                 '<option value="',lc,'" style="font-family:',ff,';"',
609                     (this.defaultFont == lc ? ' selected="true">' : '>'),
610                     ff,
611                 '</option>'
612             );
613         }
614         return buf.join('');
615     },
616     
617     toggleSourceEdit : function(sourceEditMode){
618         
619         Roo.log("toolbar toogle");
620         if(sourceEditMode === undefined){
621             sourceEditMode = !this.sourceEditMode;
622         }
623         this.sourceEditMode = sourceEditMode === true;
624         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
625         // just toggle the button?
626         if(btn.pressed !== this.sourceEditMode){
627             btn.toggle(this.sourceEditMode);
628             return;
629         }
630         
631         if(sourceEditMode){
632             Roo.log("disabling buttons");
633             this.tb.items.each(function(item){
634                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
635                     item.disable();
636                 }
637             });
638           
639         }else{
640             Roo.log("enabling buttons");
641             if(this.editorcore.initialized){
642                 this.tb.items.each(function(item){
643                     item.enable();
644                 });
645             }
646             
647         }
648         Roo.log("calling toggole on editor");
649         // tell the editor that it's been pressed..
650         this.editor.toggleSourceEdit(sourceEditMode);
651        
652     },
653      /**
654      * Object collection of toolbar tooltips for the buttons in the editor. The key
655      * is the command id associated with that button and the value is a valid QuickTips object.
656      * For example:
657 <pre><code>
658 {
659     bold : {
660         title: 'Bold (Ctrl+B)',
661         text: 'Make the selected text bold.',
662         cls: 'x-html-editor-tip'
663     },
664     italic : {
665         title: 'Italic (Ctrl+I)',
666         text: 'Make the selected text italic.',
667         cls: 'x-html-editor-tip'
668     },
669     ...
670 </code></pre>
671     * @type Object
672      */
673     buttonTips : {
674         bold : {
675             title: 'Bold (Ctrl+B)',
676             text: 'Make the selected text bold.',
677             cls: 'x-html-editor-tip'
678         },
679         italic : {
680             title: 'Italic (Ctrl+I)',
681             text: 'Make the selected text italic.',
682             cls: 'x-html-editor-tip'
683         },
684         underline : {
685             title: 'Underline (Ctrl+U)',
686             text: 'Underline the selected text.',
687             cls: 'x-html-editor-tip'
688         },
689         strikethrough : {
690             title: 'Strikethrough',
691             text: 'Strikethrough the selected text.',
692             cls: 'x-html-editor-tip'
693         },
694         increasefontsize : {
695             title: 'Grow Text',
696             text: 'Increase the font size.',
697             cls: 'x-html-editor-tip'
698         },
699         decreasefontsize : {
700             title: 'Shrink Text',
701             text: 'Decrease the font size.',
702             cls: 'x-html-editor-tip'
703         },
704         backcolor : {
705             title: 'Text Highlight Color',
706             text: 'Change the background color of the selected text.',
707             cls: 'x-html-editor-tip'
708         },
709         forecolor : {
710             title: 'Font Color',
711             text: 'Change the color of the selected text.',
712             cls: 'x-html-editor-tip'
713         },
714         justifyleft : {
715             title: 'Align Text Left',
716             text: 'Align text to the left.',
717             cls: 'x-html-editor-tip'
718         },
719         justifycenter : {
720             title: 'Center Text',
721             text: 'Center text in the editor.',
722             cls: 'x-html-editor-tip'
723         },
724         justifyright : {
725             title: 'Align Text Right',
726             text: 'Align text to the right.',
727             cls: 'x-html-editor-tip'
728         },
729         insertunorderedlist : {
730             title: 'Bullet List',
731             text: 'Start a bulleted list.',
732             cls: 'x-html-editor-tip'
733         },
734         insertorderedlist : {
735             title: 'Numbered List',
736             text: 'Start a numbered list.',
737             cls: 'x-html-editor-tip'
738         },
739         createlink : {
740             title: 'Hyperlink',
741             text: 'Make the selected text a hyperlink.',
742             cls: 'x-html-editor-tip'
743         },
744         sourceedit : {
745             title: 'Source Edit',
746             text: 'Switch to source editing mode.',
747             cls: 'x-html-editor-tip'
748         }
749     },
750     // private
751     onDestroy : function(){
752         if(this.rendered){
753             
754             this.tb.items.each(function(item){
755                 if(item.menu){
756                     item.menu.removeAll();
757                     if(item.menu.el){
758                         item.menu.el.destroy();
759                     }
760                 }
761                 item.destroy();
762             });
763              
764         }
765     },
766     onFirstFocus: function() {
767         this.tb.items.each(function(item){
768            item.enable();
769         });
770     }
771 });
772
773
774
775