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                 btn('strikethrough')
243                         
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.className = '';
439                     });
440                     editorcore.syncValue();
441                 },
442                 tabIndex:-1
443             });
444             
445              cmenu.menu.items.push({
446                 actiontype : 'tidy',
447                 html: 'Tidy HTML Source',
448                 handler: function(a,b) {
449                     editorcore.doc.body.innerHTML = editorcore.domToHTML();
450                     editorcore.syncValue();
451                 },
452                 tabIndex:-1
453             });
454             
455             
456             tb.add(cmenu);
457         }
458          
459         if (!this.disable.specialElements) {
460             var semenu = {
461                 text: "Other;",
462                 cls: 'x-edit-none',
463                 menu : {
464                     items : []
465                 }
466             };
467             for (var i =0; i < this.specialElements.length; i++) {
468                 semenu.menu.items.push(
469                     Roo.apply({ 
470                         handler: function(a,b) {
471                             editor.insertAtCursor(this.ihtml);
472                         }
473                     }, this.specialElements[i])
474                 );
475                     
476             }
477             
478             tb.add(semenu);
479             
480             
481         }
482          
483         
484         if (this.btns) {
485             for(var i =0; i< this.btns.length;i++) {
486                 var b = Roo.factory(this.btns[i],Roo.form);
487                 b.cls =  'x-edit-none';
488                 
489                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
490                     b.cls += ' x-init-enable';
491                 }
492                 
493                 b.scope = editorcore;
494                 tb.add(b);
495             }
496         
497         }
498         
499         
500         
501         // disable everything...
502         
503         this.tb.items.each(function(item){
504             
505            if(
506                 item.id != editorcore.frameId+ '-sourceedit' && 
507                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
508             ){
509                 
510                 item.disable();
511             }
512         });
513         this.rendered = true;
514         
515         // the all the btns;
516         editor.on('editorevent', this.updateToolbar, this);
517         // other toolbars need to implement this..
518         //editor.on('editmodechange', this.updateToolbar, this);
519     },
520     
521     
522     relayBtnCmd : function(btn) {
523         this.editorcore.relayCmd(btn.cmd);
524     },
525     // private used internally
526     createLink : function(){
527         Roo.log("create link?");
528         var url = prompt(this.createLinkText, this.defaultLinkValue);
529         if(url && url != 'http:/'+'/'){
530             this.editorcore.relayCmd('createlink', url);
531         }
532     },
533
534     
535     /**
536      * Protected method that will not generally be called directly. It triggers
537      * a toolbar update by reading the markup state of the current selection in the editor.
538      */
539     updateToolbar: function(){
540
541         if(!this.editorcore.activated){
542             this.editor.onFirstFocus();
543             return;
544         }
545
546         var btns = this.tb.items.map, 
547             doc = this.editorcore.doc,
548             frameId = this.editorcore.frameId;
549
550         if(!this.disable.font && !Roo.isSafari){
551             /*
552             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
553             if(name != this.fontSelect.dom.value){
554                 this.fontSelect.dom.value = name;
555             }
556             */
557         }
558         if(!this.disable.format){
559             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
560             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
561             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
562             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
563         }
564         if(!this.disable.alignments){
565             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
566             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
567             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
568         }
569         if(!Roo.isSafari && !this.disable.lists){
570             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
571             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
572         }
573         
574         var ans = this.editorcore.getAllAncestors();
575         if (this.formatCombo) {
576             
577             
578             var store = this.formatCombo.store;
579             this.formatCombo.setValue("");
580             for (var i =0; i < ans.length;i++) {
581                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
582                     // select it..
583                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
584                     break;
585                 }
586             }
587         }
588         
589         
590         
591         // hides menus... - so this cant be on a menu...
592         Roo.menu.MenuMgr.hideAll();
593
594         //this.editorsyncValue();
595     },
596    
597     
598     createFontOptions : function(){
599         var buf = [], fs = this.fontFamilies, ff, lc;
600         
601         
602         
603         for(var i = 0, len = fs.length; i< len; i++){
604             ff = fs[i];
605             lc = ff.toLowerCase();
606             buf.push(
607                 '<option value="',lc,'" style="font-family:',ff,';"',
608                     (this.defaultFont == lc ? ' selected="true">' : '>'),
609                     ff,
610                 '</option>'
611             );
612         }
613         return buf.join('');
614     },
615     
616     toggleSourceEdit : function(sourceEditMode){
617         
618         Roo.log("toolbar toogle");
619         if(sourceEditMode === undefined){
620             sourceEditMode = !this.sourceEditMode;
621         }
622         this.sourceEditMode = sourceEditMode === true;
623         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
624         // just toggle the button?
625         if(btn.pressed !== this.sourceEditMode){
626             btn.toggle(this.sourceEditMode);
627             return;
628         }
629         
630         if(sourceEditMode){
631             Roo.log("disabling buttons");
632             this.tb.items.each(function(item){
633                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
634                     item.disable();
635                 }
636             });
637           
638         }else{
639             Roo.log("enabling buttons");
640             if(this.editorcore.initialized){
641                 this.tb.items.each(function(item){
642                     item.enable();
643                 });
644             }
645             
646         }
647         Roo.log("calling toggole on editor");
648         // tell the editor that it's been pressed..
649         this.editor.toggleSourceEdit(sourceEditMode);
650        
651     },
652      /**
653      * Object collection of toolbar tooltips for the buttons in the editor. The key
654      * is the command id associated with that button and the value is a valid QuickTips object.
655      * For example:
656 <pre><code>
657 {
658     bold : {
659         title: 'Bold (Ctrl+B)',
660         text: 'Make the selected text bold.',
661         cls: 'x-html-editor-tip'
662     },
663     italic : {
664         title: 'Italic (Ctrl+I)',
665         text: 'Make the selected text italic.',
666         cls: 'x-html-editor-tip'
667     },
668     ...
669 </code></pre>
670     * @type Object
671      */
672     buttonTips : {
673         bold : {
674             title: 'Bold (Ctrl+B)',
675             text: 'Make the selected text bold.',
676             cls: 'x-html-editor-tip'
677         },
678         italic : {
679             title: 'Italic (Ctrl+I)',
680             text: 'Make the selected text italic.',
681             cls: 'x-html-editor-tip'
682         },
683         underline : {
684             title: 'Underline (Ctrl+U)',
685             text: 'Underline the selected text.',
686             cls: 'x-html-editor-tip'
687         },
688         strikethrough : {
689             title: 'Strikethrough',
690             text: 'Strikethrough the selected text.',
691             cls: 'x-html-editor-tip'
692         },
693         increasefontsize : {
694             title: 'Grow Text',
695             text: 'Increase the font size.',
696             cls: 'x-html-editor-tip'
697         },
698         decreasefontsize : {
699             title: 'Shrink Text',
700             text: 'Decrease the font size.',
701             cls: 'x-html-editor-tip'
702         },
703         backcolor : {
704             title: 'Text Highlight Color',
705             text: 'Change the background color of the selected text.',
706             cls: 'x-html-editor-tip'
707         },
708         forecolor : {
709             title: 'Font Color',
710             text: 'Change the color of the selected text.',
711             cls: 'x-html-editor-tip'
712         },
713         justifyleft : {
714             title: 'Align Text Left',
715             text: 'Align text to the left.',
716             cls: 'x-html-editor-tip'
717         },
718         justifycenter : {
719             title: 'Center Text',
720             text: 'Center text in the editor.',
721             cls: 'x-html-editor-tip'
722         },
723         justifyright : {
724             title: 'Align Text Right',
725             text: 'Align text to the right.',
726             cls: 'x-html-editor-tip'
727         },
728         insertunorderedlist : {
729             title: 'Bullet List',
730             text: 'Start a bulleted list.',
731             cls: 'x-html-editor-tip'
732         },
733         insertorderedlist : {
734             title: 'Numbered List',
735             text: 'Start a numbered list.',
736             cls: 'x-html-editor-tip'
737         },
738         createlink : {
739             title: 'Hyperlink',
740             text: 'Make the selected text a hyperlink.',
741             cls: 'x-html-editor-tip'
742         },
743         sourceedit : {
744             title: 'Source Edit',
745             text: 'Switch to source editing mode.',
746             cls: 'x-html-editor-tip'
747         }
748     },
749     // private
750     onDestroy : function(){
751         if(this.rendered){
752             
753             this.tb.items.each(function(item){
754                 if(item.menu){
755                     item.menu.removeAll();
756                     if(item.menu.el){
757                         item.menu.el.destroy();
758                     }
759                 }
760                 item.destroy();
761             });
762              
763         }
764     },
765     onFirstFocus: function() {
766         this.tb.items.each(function(item){
767            item.enable();
768         });
769     }
770 });
771
772
773
774