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