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