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