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