2f5565cdd209cfd6f4a57db0dd7bd7be15895d4f
[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                 btn('strikethrough')
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                         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                         editorcore.syncValue();
393                     },
394                     tabIndex:-1
395                 });
396             }
397              cmenu.menu.items.push({
398                 actiontype : 'tablewidths',
399                 html: 'Remove Table Widths',
400                 handler: function(a,b) {
401                     editorcore.cleanTableWidths();
402                     editorcore.syncValue();
403                 },
404                 tabIndex:-1
405             });
406             cmenu.menu.items.push({
407                 actiontype : 'word',
408                 html: 'Remove MS Word Formating',
409                 handler: function(a,b) {
410                     editorcore.cleanWord();
411                     editorcore.syncValue();
412                 },
413                 tabIndex:-1
414             });
415             
416             cmenu.menu.items.push({
417                 actiontype : 'all',
418                 html: 'Remove All Styles',
419                 handler: function(a,b) {
420                     
421                     var c = Roo.get(editorcore.doc.body);
422                     c.select('[style]').each(function(s) {
423                         s.dom.removeAttribute('style');
424                     });
425                     editorcore.syncValue();
426                 },
427                 tabIndex:-1
428             });
429             
430             cmenu.menu.items.push({
431                 actiontype : 'all',
432                 html: 'Remove All CSS Classes',
433                 handler: function(a,b) {
434                     
435                     var c = Roo.get(editorcore.doc.body);
436                     c.select('[class]').each(function(s) {
437                         s.dom.className = '';
438                     });
439                     editorcore.syncValue();
440                 },
441                 tabIndex:-1
442             });
443             
444              cmenu.menu.items.push({
445                 actiontype : 'tidy',
446                 html: 'Tidy HTML Source',
447                 handler: function(a,b) {
448                     editorcore.doc.body.innerHTML = editorcore.domToHTML();
449                     editorcore.syncValue();
450                 },
451                 tabIndex:-1
452             });
453             
454             
455             tb.add(cmenu);
456         }
457          
458         if (!this.disable.specialElements) {
459             var semenu = {
460                 text: "Other;",
461                 cls: 'x-edit-none',
462                 menu : {
463                     items : []
464                 }
465             };
466             for (var i =0; i < this.specialElements.length; i++) {
467                 semenu.menu.items.push(
468                     Roo.apply({ 
469                         handler: function(a,b) {
470                             editor.insertAtCursor(this.ihtml);
471                         }
472                     }, this.specialElements[i])
473                 );
474                     
475             }
476             
477             tb.add(semenu);
478             
479             
480         }
481          
482         
483         if (this.btns) {
484             for(var i =0; i< this.btns.length;i++) {
485                 var b = Roo.factory(this.btns[i],Roo.form);
486                 b.cls =  'x-edit-none';
487                 
488                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
489                     b.cls += ' x-init-enable';
490                 }
491                 
492                 b.scope = editorcore;
493                 tb.add(b);
494             }
495         
496         }
497         
498         
499         
500         // disable everything...
501         
502         this.tb.items.each(function(item){
503             
504            if(
505                 item.id != editorcore.frameId+ '-sourceedit' && 
506                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
507             ){
508                 
509                 item.disable();
510             }
511         });
512         this.rendered = true;
513         
514         // the all the btns;
515         editor.on('editorevent', this.updateToolbar, this);
516         // other toolbars need to implement this..
517         //editor.on('editmodechange', this.updateToolbar, this);
518     },
519     
520     
521     relayBtnCmd : function(btn) {
522         this.editorcore.relayCmd(btn.cmd);
523     },
524     // private used internally
525     createLink : function(){
526         Roo.log("create link?");
527         var url = prompt(this.createLinkText, this.defaultLinkValue);
528         if(url && url != 'http:/'+'/'){
529             this.editorcore.relayCmd('createlink', url);
530         }
531     },
532
533     
534     /**
535      * Protected method that will not generally be called directly. It triggers
536      * a toolbar update by reading the markup state of the current selection in the editor.
537      */
538     updateToolbar: function(){
539
540         if(!this.editorcore.activated){
541             this.editor.onFirstFocus();
542             return;
543         }
544
545         var btns = this.tb.items.map, 
546             doc = this.editorcore.doc,
547             frameId = this.editorcore.frameId;
548
549         if(!this.disable.font && !Roo.isSafari){
550             /*
551             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
552             if(name != this.fontSelect.dom.value){
553                 this.fontSelect.dom.value = name;
554             }
555             */
556         }
557         if(!this.disable.format){
558             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
559             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
560             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
561             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
562         }
563         if(!this.disable.alignments){
564             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
565             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
566             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
567         }
568         if(!Roo.isSafari && !this.disable.lists){
569             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
570             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
571         }
572         
573         var ans = this.editorcore.getAllAncestors();
574         if (this.formatCombo) {
575             
576             
577             var store = this.formatCombo.store;
578             this.formatCombo.setValue("");
579             for (var i =0; i < ans.length;i++) {
580                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
581                     // select it..
582                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
583                     break;
584                 }
585             }
586         }
587         
588         
589         
590         // hides menus... - so this cant be on a menu...
591         Roo.menu.MenuMgr.hideAll();
592
593         //this.editorsyncValue();
594     },
595    
596     
597     createFontOptions : function(){
598         var buf = [], fs = this.fontFamilies, ff, lc;
599         
600         
601         
602         for(var i = 0, len = fs.length; i< len; i++){
603             ff = fs[i];
604             lc = ff.toLowerCase();
605             buf.push(
606                 '<option value="',lc,'" style="font-family:',ff,';"',
607                     (this.defaultFont == lc ? ' selected="true">' : '>'),
608                     ff,
609                 '</option>'
610             );
611         }
612         return buf.join('');
613     },
614     
615     toggleSourceEdit : function(sourceEditMode){
616         
617         Roo.log("toolbar toogle");
618         if(sourceEditMode === undefined){
619             sourceEditMode = !this.sourceEditMode;
620         }
621         this.sourceEditMode = sourceEditMode === true;
622         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
623         // just toggle the button?
624         if(btn.pressed !== this.sourceEditMode){
625             btn.toggle(this.sourceEditMode);
626             return;
627         }
628         
629         if(sourceEditMode){
630             Roo.log("disabling buttons");
631             this.tb.items.each(function(item){
632                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
633                     item.disable();
634                 }
635             });
636           
637         }else{
638             Roo.log("enabling buttons");
639             if(this.editorcore.initialized){
640                 this.tb.items.each(function(item){
641                     item.enable();
642                 });
643             }
644             
645         }
646         Roo.log("calling toggole on editor");
647         // tell the editor that it's been pressed..
648         this.editor.toggleSourceEdit(sourceEditMode);
649        
650     },
651      /**
652      * Object collection of toolbar tooltips for the buttons in the editor. The key
653      * is the command id associated with that button and the value is a valid QuickTips object.
654      * For example:
655 <pre><code>
656 {
657     bold : {
658         title: 'Bold (Ctrl+B)',
659         text: 'Make the selected text bold.',
660         cls: 'x-html-editor-tip'
661     },
662     italic : {
663         title: 'Italic (Ctrl+I)',
664         text: 'Make the selected text italic.',
665         cls: 'x-html-editor-tip'
666     },
667     ...
668 </code></pre>
669     * @type Object
670      */
671     buttonTips : {
672         bold : {
673             title: 'Bold (Ctrl+B)',
674             text: 'Make the selected text bold.',
675             cls: 'x-html-editor-tip'
676         },
677         italic : {
678             title: 'Italic (Ctrl+I)',
679             text: 'Make the selected text italic.',
680             cls: 'x-html-editor-tip'
681         },
682         underline : {
683             title: 'Underline (Ctrl+U)',
684             text: 'Underline the selected text.',
685             cls: 'x-html-editor-tip'
686         },
687         strikethrough : {
688             title: 'Strikethrough',
689             text: 'Strikethrough the selected text.',
690             cls: 'x-html-editor-tip'
691         },
692         increasefontsize : {
693             title: 'Grow Text',
694             text: 'Increase the font size.',
695             cls: 'x-html-editor-tip'
696         },
697         decreasefontsize : {
698             title: 'Shrink Text',
699             text: 'Decrease the font size.',
700             cls: 'x-html-editor-tip'
701         },
702         backcolor : {
703             title: 'Text Highlight Color',
704             text: 'Change the background color of the selected text.',
705             cls: 'x-html-editor-tip'
706         },
707         forecolor : {
708             title: 'Font Color',
709             text: 'Change the color of the selected text.',
710             cls: 'x-html-editor-tip'
711         },
712         justifyleft : {
713             title: 'Align Text Left',
714             text: 'Align text to the left.',
715             cls: 'x-html-editor-tip'
716         },
717         justifycenter : {
718             title: 'Center Text',
719             text: 'Center text in the editor.',
720             cls: 'x-html-editor-tip'
721         },
722         justifyright : {
723             title: 'Align Text Right',
724             text: 'Align text to the right.',
725             cls: 'x-html-editor-tip'
726         },
727         insertunorderedlist : {
728             title: 'Bullet List',
729             text: 'Start a bulleted list.',
730             cls: 'x-html-editor-tip'
731         },
732         insertorderedlist : {
733             title: 'Numbered List',
734             text: 'Start a numbered list.',
735             cls: 'x-html-editor-tip'
736         },
737         createlink : {
738             title: 'Hyperlink',
739             text: 'Make the selected text a hyperlink.',
740             cls: 'x-html-editor-tip'
741         },
742         sourceedit : {
743             title: 'Source Edit',
744             text: 'Switch to source editing mode.',
745             cls: 'x-html-editor-tip'
746         }
747     },
748     // private
749     onDestroy : function(){
750         if(this.rendered){
751             
752             this.tb.items.each(function(item){
753                 if(item.menu){
754                     item.menu.removeAll();
755                     if(item.menu.el){
756                         item.menu.el.destroy();
757                     }
758                 }
759                 item.destroy();
760             });
761              
762         }
763     },
764     onFirstFocus: function() {
765         this.tb.items.each(function(item){
766            item.enable();
767         });
768     }
769 });
770
771
772
773