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     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     ],
137     
138     cleanStyles : [
139         "font-size"
140     ],
141      /**
142      * @cfg {String} defaultFont default font to use.
143      */
144     defaultFont: 'tahoma',
145    
146     fontSelect : false,
147     
148     
149     formatCombo : false,
150     
151     init : function(editor)
152     {
153         this.editor = editor;
154         this.editorcore = editor.editorcore ? editor.editorcore : editor;
155         var editorcore = this.editorcore;
156         
157         var _t = this;
158         
159         var fid = editorcore.frameId;
160         var etb = this;
161         function btn(id, toggle, handler){
162             var xid = fid + '-'+ id ;
163             return {
164                 id : xid,
165                 cmd : id,
166                 cls : 'x-btn-icon x-edit-'+id,
167                 enableToggle:toggle !== false,
168                 scope: _t, // was editor...
169                 handler:handler||_t.relayBtnCmd,
170                 clickEvent:'mousedown',
171                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
172                 tabIndex:-1
173             };
174         }
175         
176         
177         
178         var tb = new Roo.Toolbar(editor.wrap.dom.firstChild);
179         this.tb = tb;
180          // stop form submits
181         tb.el.on('click', function(e){
182             e.preventDefault(); // what does this do?
183         });
184
185         if(!this.disable.font) { // && !Roo.isSafari){
186             /* why no safari for fonts 
187             editor.fontSelect = tb.el.createChild({
188                 tag:'select',
189                 tabIndex: -1,
190                 cls:'x-font-select',
191                 html: this.createFontOptions()
192             });
193             
194             editor.fontSelect.on('change', function(){
195                 var font = editor.fontSelect.dom.value;
196                 editor.relayCmd('fontname', font);
197                 editor.deferFocus();
198             }, editor);
199             
200             tb.add(
201                 editor.fontSelect.dom,
202                 '-'
203             );
204             */
205             
206         };
207         if(!this.disable.formats){
208             this.formatCombo = new Roo.form.ComboBox({
209                 store: new Roo.data.SimpleStore({
210                     id : 'tag',
211                     fields: ['tag'],
212                     data : this.formats // from states.js
213                 }),
214                 blockFocus : true,
215                 name : '',
216                 //autoCreate : {tag: "div",  size: "20"},
217                 displayField:'tag',
218                 typeAhead: false,
219                 mode: 'local',
220                 editable : false,
221                 triggerAction: 'all',
222                 emptyText:'Add tag',
223                 selectOnFocus:true,
224                 width:135,
225                 listeners : {
226                     'select': function(c, r, i) {
227                         editorcore.insertTag(r.get('tag'));
228                         editor.focus();
229                     }
230                 }
231
232             });
233             tb.addField(this.formatCombo);
234             
235         }
236         
237         if(!this.disable.format){
238             tb.add(
239                 btn('bold'),
240                 btn('italic'),
241                 btn('underline')
242             );
243         };
244         if(!this.disable.fontSize){
245             tb.add(
246                 '-',
247                 
248                 
249                 btn('increasefontsize', false, editorcore.adjustFont),
250                 btn('decreasefontsize', false, editorcore.adjustFont)
251             );
252         };
253         
254         
255         if(!this.disable.colors){
256             tb.add(
257                 '-', {
258                     id:editorcore.frameId +'-forecolor',
259                     cls:'x-btn-icon x-edit-forecolor',
260                     clickEvent:'mousedown',
261                     tooltip: this.buttonTips['forecolor'] || undefined,
262                     tabIndex:-1,
263                     menu : new Roo.menu.ColorMenu({
264                         allowReselect: true,
265                         focus: Roo.emptyFn,
266                         value:'000000',
267                         plain:true,
268                         selectHandler: function(cp, color){
269                             editorcore.execCmd('forecolor', Roo.isSafari || Roo.isIE ? '#'+color : color);
270                             editor.deferFocus();
271                         },
272                         scope: editorcore,
273                         clickEvent:'mousedown'
274                     })
275                 }, {
276                     id:editorcore.frameId +'backcolor',
277                     cls:'x-btn-icon x-edit-backcolor',
278                     clickEvent:'mousedown',
279                     tooltip: this.buttonTips['backcolor'] || undefined,
280                     tabIndex:-1,
281                     menu : new Roo.menu.ColorMenu({
282                         focus: Roo.emptyFn,
283                         value:'FFFFFF',
284                         plain:true,
285                         allowReselect: true,
286                         selectHandler: function(cp, color){
287                             if(Roo.isGecko){
288                                 editorcore.execCmd('useCSS', false);
289                                 editorcore.execCmd('hilitecolor', color);
290                                 editorcore.execCmd('useCSS', true);
291                                 editor.deferFocus();
292                             }else{
293                                 editorcore.execCmd(Roo.isOpera ? 'hilitecolor' : 'backcolor', 
294                                     Roo.isSafari || Roo.isIE ? '#'+color : color);
295                                 editor.deferFocus();
296                             }
297                         },
298                         scope:editorcore,
299                         clickEvent:'mousedown'
300                     })
301                 }
302             );
303         };
304         // now add all the items...
305         
306
307         if(!this.disable.alignments){
308             tb.add(
309                 '-',
310                 btn('justifyleft'),
311                 btn('justifycenter'),
312                 btn('justifyright')
313             );
314         };
315
316         //if(!Roo.isSafari){
317             if(!this.disable.links){
318                 tb.add(
319                     '-',
320                     btn('createlink', false, this.createLink)    /// MOVE TO HERE?!!?!?!?!
321                 );
322             };
323
324             if(!this.disable.lists){
325                 tb.add(
326                     '-',
327                     btn('insertorderedlist'),
328                     btn('insertunorderedlist')
329                 );
330             }
331             if(!this.disable.sourceEdit){
332                 tb.add(
333                     '-',
334                     btn('sourceedit', true, function(btn){
335                         this.toggleSourceEdit(btn.pressed);
336                     })
337                 );
338             }
339         //}
340         
341         var smenu = { };
342         // special menu.. - needs to be tidied up..
343         if (!this.disable.special) {
344             smenu = {
345                 text: "&#169;",
346                 cls: 'x-edit-none',
347                 
348                 menu : {
349                     items : []
350                 }
351             };
352             for (var i =0; i < this.specialChars.length; i++) {
353                 smenu.menu.items.push({
354                     
355                     html: this.specialChars[i],
356                     handler: function(a,b) {
357                         editorcore.insertAtCursor(String.fromCharCode(a.html.replace('&#','').replace(';', '')));
358                         //editor.insertAtCursor(a.html);
359                         
360                     },
361                     tabIndex:-1
362                 });
363             }
364             
365             
366             tb.add(smenu);
367             
368             
369         }
370         
371         var cmenu = { };
372         if (!this.disable.cleanStyles) {
373             cmenu = {
374                 cls: 'x-btn-icon x-btn-clear',
375                 
376                 menu : {
377                     items : []
378                 }
379             };
380             for (var i =0; i < this.cleanStyles.length; i++) {
381                 cmenu.menu.items.push({
382                     actiontype : this.cleanStyles[i],
383                     html: 'Remove ' + this.cleanStyles[i],
384                     handler: function(a,b) {
385 //                        Roo.log(a);
386 //                        Roo.log(b);
387                         var c = Roo.get(editorcore.doc.body);
388                         c.select('[style]').each(function(s) {
389                             s.dom.style.removeProperty(a.actiontype);
390                         });
391                         editorcore.syncValue();
392                     },
393                     tabIndex:-1
394                 });
395             }
396              cmenu.menu.items.push({
397                 actiontype : 'tablewidths',
398                 html: 'Remove Table Widths',
399                 handler: function(a,b) {
400                     editorcore.cleanTableWidths();
401                     editorcore.syncValue();
402                 },
403                 tabIndex:-1
404             });
405             cmenu.menu.items.push({
406                 actiontype : 'word',
407                 html: 'Remove MS Word Formating',
408                 handler: function(a,b) {
409                     editorcore.cleanWord();
410                     editorcore.syncValue();
411                 },
412                 tabIndex:-1
413             });
414             
415             cmenu.menu.items.push({
416                 actiontype : 'all',
417                 html: 'Remove All Styles',
418                 handler: function(a,b) {
419                     
420                     var c = Roo.get(editorcore.doc.body);
421                     c.select('[style]').each(function(s) {
422                         s.dom.removeAttribute('style');
423                     });
424                     editorcore.syncValue();
425                 },
426                 tabIndex:-1
427             });
428              cmenu.menu.items.push({
429                 actiontype : 'tidy',
430                 html: 'Tidy HTML Source',
431                 handler: function(a,b) {
432                     editorcore.doc.body.innerHTML = editorcore.domToHTML();
433                     editorcore.syncValue();
434                 },
435                 tabIndex:-1
436             });
437             
438             
439             tb.add(cmenu);
440         }
441          
442         if (!this.disable.specialElements) {
443             var semenu = {
444                 text: "Other;",
445                 cls: 'x-edit-none',
446                 menu : {
447                     items : []
448                 }
449             };
450             for (var i =0; i < this.specialElements.length; i++) {
451                 semenu.menu.items.push(
452                     Roo.apply({ 
453                         handler: function(a,b) {
454                             editor.insertAtCursor(this.ihtml);
455                         }
456                     }, this.specialElements[i])
457                 );
458                     
459             }
460             
461             tb.add(semenu);
462             
463             
464         }
465          
466         
467         if (this.btns) {
468             for(var i =0; i< this.btns.length;i++) {
469                 var b = Roo.factory(this.btns[i],Roo.form);
470                 b.cls =  'x-edit-none';
471                 
472                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
473                     b.cls += ' x-init-enable';
474                 }
475                 
476                 b.scope = editorcore;
477                 tb.add(b);
478             }
479         
480         }
481         
482         
483         
484         // disable everything...
485         
486         this.tb.items.each(function(item){
487             
488            if(
489                 item.id != editorcore.frameId+ '-sourceedit' && 
490                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
491             ){
492                 
493                 item.disable();
494             }
495         });
496         this.rendered = true;
497         
498         // the all the btns;
499         editor.on('editorevent', this.updateToolbar, this);
500         // other toolbars need to implement this..
501         //editor.on('editmodechange', this.updateToolbar, this);
502     },
503     
504     
505     relayBtnCmd : function(btn) {
506         this.editorcore.relayCmd(btn.cmd);
507     },
508     // private used internally
509     createLink : function(){
510         Roo.log("create link?");
511         var url = prompt(this.createLinkText, this.defaultLinkValue);
512         if(url && url != 'http:/'+'/'){
513             this.editorcore.relayCmd('createlink', url);
514         }
515     },
516
517     
518     /**
519      * Protected method that will not generally be called directly. It triggers
520      * a toolbar update by reading the markup state of the current selection in the editor.
521      */
522     updateToolbar: function(){
523
524         if(!this.editorcore.activated){
525             this.editor.onFirstFocus();
526             return;
527         }
528
529         var btns = this.tb.items.map, 
530             doc = this.editorcore.doc,
531             frameId = this.editorcore.frameId;
532
533         if(!this.disable.font && !Roo.isSafari){
534             /*
535             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
536             if(name != this.fontSelect.dom.value){
537                 this.fontSelect.dom.value = name;
538             }
539             */
540         }
541         if(!this.disable.format){
542             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
543             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
544             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
545         }
546         if(!this.disable.alignments){
547             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
548             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
549             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
550         }
551         if(!Roo.isSafari && !this.disable.lists){
552             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
553             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
554         }
555         
556         var ans = this.editorcore.getAllAncestors();
557         if (this.formatCombo) {
558             
559             
560             var store = this.formatCombo.store;
561             this.formatCombo.setValue("");
562             for (var i =0; i < ans.length;i++) {
563                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
564                     // select it..
565                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
566                     break;
567                 }
568             }
569         }
570         
571         
572         
573         // hides menus... - so this cant be on a menu...
574         Roo.menu.MenuMgr.hideAll();
575
576         //this.editorsyncValue();
577     },
578    
579     
580     createFontOptions : function(){
581         var buf = [], fs = this.fontFamilies, ff, lc;
582         
583         
584         
585         for(var i = 0, len = fs.length; i< len; i++){
586             ff = fs[i];
587             lc = ff.toLowerCase();
588             buf.push(
589                 '<option value="',lc,'" style="font-family:',ff,';"',
590                     (this.defaultFont == lc ? ' selected="true">' : '>'),
591                     ff,
592                 '</option>'
593             );
594         }
595         return buf.join('');
596     },
597     
598     toggleSourceEdit : function(sourceEditMode){
599         
600         Roo.log("toolbar toogle");
601         if(sourceEditMode === undefined){
602             sourceEditMode = !this.sourceEditMode;
603         }
604         this.sourceEditMode = sourceEditMode === true;
605         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
606         // just toggle the button?
607         if(btn.pressed !== this.sourceEditMode){
608             btn.toggle(this.sourceEditMode);
609             return;
610         }
611         
612         if(sourceEditMode){
613             Roo.log("disabling buttons");
614             this.tb.items.each(function(item){
615                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
616                     item.disable();
617                 }
618             });
619           
620         }else{
621             Roo.log("enabling buttons");
622             if(this.editorcore.initialized){
623                 this.tb.items.each(function(item){
624                     item.enable();
625                 });
626             }
627             
628         }
629         Roo.log("calling toggole on editor");
630         // tell the editor that it's been pressed..
631         this.editor.toggleSourceEdit(sourceEditMode);
632        
633     },
634      /**
635      * Object collection of toolbar tooltips for the buttons in the editor. The key
636      * is the command id associated with that button and the value is a valid QuickTips object.
637      * For example:
638 <pre><code>
639 {
640     bold : {
641         title: 'Bold (Ctrl+B)',
642         text: 'Make the selected text bold.',
643         cls: 'x-html-editor-tip'
644     },
645     italic : {
646         title: 'Italic (Ctrl+I)',
647         text: 'Make the selected text italic.',
648         cls: 'x-html-editor-tip'
649     },
650     ...
651 </code></pre>
652     * @type Object
653      */
654     buttonTips : {
655         bold : {
656             title: 'Bold (Ctrl+B)',
657             text: 'Make the selected text bold.',
658             cls: 'x-html-editor-tip'
659         },
660         italic : {
661             title: 'Italic (Ctrl+I)',
662             text: 'Make the selected text italic.',
663             cls: 'x-html-editor-tip'
664         },
665         underline : {
666             title: 'Underline (Ctrl+U)',
667             text: 'Underline the selected text.',
668             cls: 'x-html-editor-tip'
669         },
670         increasefontsize : {
671             title: 'Grow Text',
672             text: 'Increase the font size.',
673             cls: 'x-html-editor-tip'
674         },
675         decreasefontsize : {
676             title: 'Shrink Text',
677             text: 'Decrease the font size.',
678             cls: 'x-html-editor-tip'
679         },
680         backcolor : {
681             title: 'Text Highlight Color',
682             text: 'Change the background color of the selected text.',
683             cls: 'x-html-editor-tip'
684         },
685         forecolor : {
686             title: 'Font Color',
687             text: 'Change the color of the selected text.',
688             cls: 'x-html-editor-tip'
689         },
690         justifyleft : {
691             title: 'Align Text Left',
692             text: 'Align text to the left.',
693             cls: 'x-html-editor-tip'
694         },
695         justifycenter : {
696             title: 'Center Text',
697             text: 'Center text in the editor.',
698             cls: 'x-html-editor-tip'
699         },
700         justifyright : {
701             title: 'Align Text Right',
702             text: 'Align text to the right.',
703             cls: 'x-html-editor-tip'
704         },
705         insertunorderedlist : {
706             title: 'Bullet List',
707             text: 'Start a bulleted list.',
708             cls: 'x-html-editor-tip'
709         },
710         insertorderedlist : {
711             title: 'Numbered List',
712             text: 'Start a numbered list.',
713             cls: 'x-html-editor-tip'
714         },
715         createlink : {
716             title: 'Hyperlink',
717             text: 'Make the selected text a hyperlink.',
718             cls: 'x-html-editor-tip'
719         },
720         sourceedit : {
721             title: 'Source Edit',
722             text: 'Switch to source editing mode.',
723             cls: 'x-html-editor-tip'
724         }
725     },
726     // private
727     onDestroy : function(){
728         if(this.rendered){
729             
730             this.tb.items.each(function(item){
731                 if(item.menu){
732                     item.menu.removeAll();
733                     if(item.menu.el){
734                         item.menu.el.destroy();
735                     }
736                 }
737                 item.destroy();
738             });
739              
740         }
741     },
742     onFirstFocus: function() {
743         this.tb.items.each(function(item){
744            item.enable();
745         });
746     }
747 });
748
749
750
751