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