Roo/form/HtmlEditor/ToolbarStandard.js
[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     /**
60      * @cfg {Object} disable  List of toolbar elements to disable
61          
62      */
63     disable : false,
64       /**
65      * @cfg {Array} fontFamilies An array of available font families
66      */
67     fontFamilies : [
68         'Arial',
69         'Courier New',
70         'Tahoma',
71         'Times New Roman',
72         'Verdana'
73     ],
74     
75     specialChars : [
76            "&#169;",
77           "&#174;",     
78           "&#8482;",    
79           "&#163;" ,    
80          // "&#8212;",    
81           "&#8230;",    
82           "&#247;" ,    
83         //  "&#225;" ,     ?? a acute?
84            "&#8364;"    , //Euro
85        //   "&#8220;"    ,
86         //  "&#8221;"    ,
87         //  "&#8226;"    ,
88           "&#176;"  //   , // degrees
89
90          // "&#233;"     , // e ecute
91          // "&#250;"     , // u ecute?
92     ],
93     
94     specialElements : [
95         {
96             text: "Insert Table",
97             xtype: 'MenuItem',
98             xns : Roo.Menu,
99             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
100                 
101         },
102         {    
103             text: "Insert Image",
104             xtype: 'MenuItem',
105             xns : Roo.Menu,
106             ihtml : '<img src="about:blank"/>'
107             
108         }
109         
110          
111     ],
112     
113     
114     inputElements : [ 
115             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
116             "input:submit", "input:button", "select", "textarea", "label" ],
117     formats : [
118         ["p"] ,  
119         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
120         ["pre"],[ "code"], 
121         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
122         ['div'],['span']
123     ],
124     
125     cleanStyles : [
126         "font-size"
127     ],
128      /**
129      * @cfg {String} defaultFont default font to use.
130      */
131     defaultFont: 'tahoma',
132    
133     fontSelect : false,
134     
135     
136     formatCombo : false,
137     
138     init : function(editor)
139     {
140         this.editor = editor;
141         
142         
143         var fid = editor.frameId;
144         var etb = this;
145         function btn(id, toggle, handler){
146             var xid = fid + '-'+ id ;
147             return {
148                 id : xid,
149                 cmd : id,
150                 cls : 'x-btn-icon x-edit-'+id,
151                 enableToggle:toggle !== false,
152                 scope: editor, // was editor...
153                 handler:handler||editor.relayBtnCmd,
154                 clickEvent:'mousedown',
155                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
156                 tabIndex:-1
157             };
158         }
159         
160         
161         
162         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
163         this.tb = tb;
164          // stop form submits
165         tb.el.on('click', function(e){
166             e.preventDefault(); // what does this do?
167         });
168
169         if(!this.disable.font) { // && !Roo.isSafari){
170             /* why no safari for fonts 
171             editor.fontSelect = tb.el.createChild({
172                 tag:'select',
173                 tabIndex: -1,
174                 cls:'x-font-select',
175                 html: this.createFontOptions()
176             });
177             
178             editor.fontSelect.on('change', function(){
179                 var font = editor.fontSelect.dom.value;
180                 editor.relayCmd('fontname', font);
181                 editor.deferFocus();
182             }, editor);
183             
184             tb.add(
185                 editor.fontSelect.dom,
186                 '-'
187             );
188             */
189             
190         };
191         if(!this.disable.formats){
192             this.formatCombo = new Roo.form.ComboBox({
193                 store: new Roo.data.SimpleStore({
194                     id : 'tag',
195                     fields: ['tag'],
196                     data : this.formats // from states.js
197                 }),
198                 blockFocus : true,
199                 name : '',
200                 //autoCreate : {tag: "div",  size: "20"},
201                 displayField:'tag',
202                 typeAhead: false,
203                 mode: 'local',
204                 editable : false,
205                 triggerAction: 'all',
206                 emptyText:'Add tag',
207                 selectOnFocus:true,
208                 width:135,
209                 listeners : {
210                     'select': function(c, r, i) {
211                         editor.insertTag(r.get('tag'));
212                         editor.focus();
213                     }
214                 }
215
216             });
217             tb.addField(this.formatCombo);
218             
219         }
220         
221         if(!this.disable.format){
222             tb.add(
223                 btn('bold'),
224                 btn('italic'),
225                 btn('underline')
226             );
227         };
228         if(!this.disable.fontSize){
229             tb.add(
230                 '-',
231                 
232                 
233                 btn('increasefontsize', false, editor.adjustFont),
234                 btn('decreasefontsize', false, editor.adjustFont)
235             );
236         };
237         
238         
239         if(!this.disable.colors){
240             tb.add(
241                 '-', {
242                     id:editor.frameId +'-forecolor',
243                     cls:'x-btn-icon x-edit-forecolor',
244                     clickEvent:'mousedown',
245                     tooltip: this.buttonTips['forecolor'] || undefined,
246                     tabIndex:-1,
247                     menu : new Roo.menu.ColorMenu({
248                         allowReselect: true,
249                         focus: Roo.emptyFn,
250                         value:'000000',
251                         plain:true,
252                         selectHandler: function(cp, color){
253                             editor.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
254                             editor.deferFocus();
255                         },
256                         scope: editor,
257                         clickEvent:'mousedown'
258                     })
259                 }, {
260                     id:editor.frameId +'backcolor',
261                     cls:'x-btn-icon x-edit-backcolor',
262                     clickEvent:'mousedown',
263                     tooltip: this.buttonTips['backcolor'] || undefined,
264                     tabIndex:-1,
265                     menu : new Roo.menu.ColorMenu({
266                         focus: Roo.emptyFn,
267                         value:'FFFFFF',
268                         plain:true,
269                         allowReselect: true,
270                         selectHandler: function(cp, color){
271                             if(Roo.isGecko){
272                                 editor.execCmd('useCSS', false);
273                                 editor.execCmd('hilitecolor', color);
274                                 editor.execCmd('useCSS', true);
275                                 editor.deferFocus();
276                             }else{
277                                 editor.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
278                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
279                                 editor.deferFocus();
280                             }
281                         },
282                         scope:editor,
283                         clickEvent:'mousedown'
284                     })
285                 }
286             );
287         };
288         // now add all the items...
289         
290
291         if(!this.disable.alignments){
292             tb.add(
293                 '-',
294                 btn('justifyleft'),
295                 btn('justifycenter'),
296                 btn('justifyright')
297             );
298         };
299
300         //if(!Roo.isSafari){
301             if(!this.disable.links){
302                 tb.add(
303                     '-',
304                     btn('createlink', false, editor.createLink)    /// MOVE TO HERE?!!?!?!?!
305                 );
306             };
307
308             if(!this.disable.lists){
309                 tb.add(
310                     '-',
311                     btn('insertorderedlist'),
312                     btn('insertunorderedlist')
313                 );
314             }
315             if(!this.disable.sourceEdit){
316                 tb.add(
317                     '-',
318                     btn('sourceedit', true, function(btn){
319                         this.toggleSourceEdit(btn.pressed);
320                     })
321                 );
322             }
323         //}
324         
325         var smenu = { };
326         // special menu.. - needs to be tidied up..
327         if (!this.disable.special) {
328             smenu = {
329                 text: "&#169;",
330                 cls: 'x-edit-none',
331                 
332                 menu : {
333                     items : []
334                 }
335             };
336             for (var i =0; i < this.specialChars.length; i++) {
337                 smenu.menu.items.push({
338                     
339                     html: this.specialChars[i],
340                     handler: function(a,b) {
341                         editor.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
342                         //editor.insertAtCursor(a.html);
343                         
344                     },
345                     tabIndex:-1
346                 });
347             }
348             
349             
350             tb.add(smenu);
351             
352             
353         }
354         
355         var cmenu = { };
356         if (!this.disable.cleanStyles) {
357             Roo.log('init toolbar style');
358             cmenu = {
359                 cls: 'x-btn-icon x-btn-clear',
360                 
361                 menu : {
362                     items : []
363                 }
364             };
365             for (var i =0; i < this.cleanStyles.length; i++) {
366                 cmenu.menu.items.push({
367                     
368                     html: this.cleanStyles[i],
369                     handler: function(a,b) {
370                         var c = Roo.get(editor.doc.body);
371                         var nodes = [];
372                         c.select('[style]').each(function(i) {
373                             Roo.log(i.dom.style);
374 //                            i.setStyle()
375                             
376                             Roo.log(i.getStyle('font-size'));
377                         });
378                         
379 //                        editor.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
380                         //editor.insertAtCursor(a.html);
381                         
382                     },
383                     tabIndex:-1
384                 });
385             }
386             
387             
388             tb.add(cmenu);
389             
390             
391         }
392          
393         if (!this.disable.specialElements) {
394             var semenu = {
395                 text: "Other;",
396                 cls: 'x-edit-none',
397                 menu : {
398                     items : []
399                 }
400             };
401             for (var i =0; i < this.specialElements.length; i++) {
402                 semenu.menu.items.push(
403                     Roo.apply({ 
404                         handler: function(a,b) {
405                             editor.insertAtCursor(this.ihtml);
406                         }
407                     }, this.specialElements[i])
408                 );
409                     
410             }
411             
412             tb.add(semenu);
413             
414             
415         }
416          
417         
418         if (this.btns) {
419             for(var i =0; i< this.btns.length;i++) {
420                 var b = Roo.factory(this.btns[i],Roo.form);
421                 b.cls =  'x-edit-none';
422                 b.scope = editor;
423                 tb.add(b);
424             }
425         
426         }
427         
428         
429         
430         // disable everything...
431         
432         this.tb.items.each(function(item){
433            if(item.id != editor.frameId+ '-sourceedit'){
434                 item.disable();
435             }
436         });
437         this.rendered = true;
438         
439         // the all the btns;
440         editor.on('editorevent', this.updateToolbar, this);
441         // other toolbars need to implement this..
442         //editor.on('editmodechange', this.updateToolbar, this);
443     },
444     
445     
446     
447     /**
448      * Protected method that will not generally be called directly. It triggers
449      * a toolbar update by reading the markup state of the current selection in the editor.
450      */
451     updateToolbar: function(){
452
453         if(!this.editor.activated){
454             this.editor.onFirstFocus();
455             return;
456         }
457
458         var btns = this.tb.items.map, 
459             doc = this.editor.doc,
460             frameId = this.editor.frameId;
461
462         if(!this.disable.font && !Roo.isSafari){
463             /*
464             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
465             if(name != this.fontSelect.dom.value){
466                 this.fontSelect.dom.value = name;
467             }
468             */
469         }
470         if(!this.disable.format){
471             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
472             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
473             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
474         }
475         if(!this.disable.alignments){
476             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
477             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
478             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
479         }
480         if(!Roo.isSafari && !this.disable.lists){
481             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
482             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
483         }
484         
485         var ans = this.editor.getAllAncestors();
486         if (this.formatCombo) {
487             
488             
489             var store = this.formatCombo.store;
490             this.formatCombo.setValue("");
491             for (var i =0; i < ans.length;i++) {
492                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
493                     // select it..
494                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
495                     break;
496                 }
497             }
498         }
499         
500         
501         
502         // hides menus... - so this cant be on a menu...
503         Roo.menu.MenuMgr.hideAll();
504
505         //this.editorsyncValue();
506     },
507    
508     
509     createFontOptions : function(){
510         var buf = [], fs = this.fontFamilies, ff, lc;
511         
512         
513         
514         for(var i = 0, len = fs.length; i< len; i++){
515             ff = fs[i];
516             lc = ff.toLowerCase();
517             buf.push(
518                 '<option value="',lc,'" style="font-family:',ff,';"',
519                     (this.defaultFont == lc ? ' selected="true">' : '>'),
520                     ff,
521                 '</option>'
522             );
523         }
524         return buf.join('');
525     },
526     
527     toggleSourceEdit : function(sourceEditMode){
528         if(sourceEditMode === undefined){
529             sourceEditMode = !this.sourceEditMode;
530         }
531         this.sourceEditMode = sourceEditMode === true;
532         var btn = this.tb.items.get(this.editor.frameId +'-sourceedit');
533         // just toggle the button?
534         if(btn.pressed !== this.editor.sourceEditMode){
535             btn.toggle(this.editor.sourceEditMode);
536             return;
537         }
538         
539         if(this.sourceEditMode){
540             this.tb.items.each(function(item){
541                 if(item.cmd != 'sourceedit'){
542                     item.disable();
543                 }
544             });
545           
546         }else{
547             if(this.initialized){
548                 this.tb.items.each(function(item){
549                     item.enable();
550                 });
551             }
552             
553         }
554         // tell the editor that it's been pressed..
555         this.editor.toggleSourceEdit(sourceEditMode);
556        
557     },
558      /**
559      * Object collection of toolbar tooltips for the buttons in the editor. The key
560      * is the command id associated with that button and the value is a valid QuickTips object.
561      * For example:
562 <pre><code>
563 {
564     bold : {
565         title: 'Bold (Ctrl+B)',
566         text: 'Make the selected text bold.',
567         cls: 'x-html-editor-tip'
568     },
569     italic : {
570         title: 'Italic (Ctrl+I)',
571         text: 'Make the selected text italic.',
572         cls: 'x-html-editor-tip'
573     },
574     ...
575 </code></pre>
576     * @type Object
577      */
578     buttonTips : {
579         bold : {
580             title: 'Bold (Ctrl+B)',
581             text: 'Make the selected text bold.',
582             cls: 'x-html-editor-tip'
583         },
584         italic : {
585             title: 'Italic (Ctrl+I)',
586             text: 'Make the selected text italic.',
587             cls: 'x-html-editor-tip'
588         },
589         underline : {
590             title: 'Underline (Ctrl+U)',
591             text: 'Underline the selected text.',
592             cls: 'x-html-editor-tip'
593         },
594         increasefontsize : {
595             title: 'Grow Text',
596             text: 'Increase the font size.',
597             cls: 'x-html-editor-tip'
598         },
599         decreasefontsize : {
600             title: 'Shrink Text',
601             text: 'Decrease the font size.',
602             cls: 'x-html-editor-tip'
603         },
604         backcolor : {
605             title: 'Text Highlight Color',
606             text: 'Change the background color of the selected text.',
607             cls: 'x-html-editor-tip'
608         },
609         forecolor : {
610             title: 'Font Color',
611             text: 'Change the color of the selected text.',
612             cls: 'x-html-editor-tip'
613         },
614         justifyleft : {
615             title: 'Align Text Left',
616             text: 'Align text to the left.',
617             cls: 'x-html-editor-tip'
618         },
619         justifycenter : {
620             title: 'Center Text',
621             text: 'Center text in the editor.',
622             cls: 'x-html-editor-tip'
623         },
624         justifyright : {
625             title: 'Align Text Right',
626             text: 'Align text to the right.',
627             cls: 'x-html-editor-tip'
628         },
629         insertunorderedlist : {
630             title: 'Bullet List',
631             text: 'Start a bulleted list.',
632             cls: 'x-html-editor-tip'
633         },
634         insertorderedlist : {
635             title: 'Numbered List',
636             text: 'Start a numbered list.',
637             cls: 'x-html-editor-tip'
638         },
639         createlink : {
640             title: 'Hyperlink',
641             text: 'Make the selected text a hyperlink.',
642             cls: 'x-html-editor-tip'
643         },
644         sourceedit : {
645             title: 'Source Edit',
646             text: 'Switch to source editing mode.',
647             cls: 'x-html-editor-tip'
648         }
649     },
650     // private
651     onDestroy : function(){
652         if(this.rendered){
653             
654             this.tb.items.each(function(item){
655                 if(item.menu){
656                     item.menu.removeAll();
657                     if(item.menu.el){
658                         item.menu.el.destroy();
659                     }
660                 }
661                 item.destroy();
662             });
663              
664         }
665     },
666     onFirstFocus: function() {
667         this.tb.items.each(function(item){
668            item.enable();
669         });
670     }
671 });
672
673
674
675