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