fix dialog on htmleditor link
[roojs1] / Roo / form / HtmlEditor / ToolbarStandard.js
1 /*
2  * Based on
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *  
6  
7  */
8
9 /**
10  * @class Roo.form.HtmlEditor.ToolbarStandard
11  * Basic Toolbar
12
13  * Usage:
14  *
15  new Roo.form.HtmlEditor({
16     ....
17     toolbars : [
18         new Roo.form.HtmlEditorToolbar1({
19             disable : { fonts: 1 , format: 1, ..., ... , ...],
20             btns : [ .... ]
21         })
22     }
23      
24  * 
25  * @cfg {Object} disable List of elements to disable..
26  * @cfg {Roo.Toolbar.Item|Roo.Toolbar.Button|Roo.Toolbar.SplitButton|Roo.form.Field} btns[] List of additional buttons.
27  * 
28  * 
29  * NEEDS Extra CSS? 
30  * .x-html-editor-tb .x-edit-none .x-btn-text { background: none; }
31  */
32  
33 Roo.form.HtmlEditor.ToolbarStandard = function(config)
34 {
35     
36     Roo.apply(this, config);
37     
38     // default disabled, based on 'good practice'..
39     this.disable = this.disable || {};
40     Roo.applyIf(this.disable, {
41         fontSize : true,
42         colors : true,
43         specialElements : true
44     });
45     
46     
47     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
48     // dont call parent... till later.
49 }
50
51 Roo.form.HtmlEditor.ToolbarStandard.prototype = {
52     
53     tb: false,
54     
55     rendered: false,
56     
57     editor : false,
58     editorcore : false,
59     /**
60      * @cfg {Object} disable  List of toolbar elements to disable
61          
62      */
63     disable : false,
64     
65     
66      /**
67      * @cfg {String} createLinkText The default text for the create link prompt
68      */
69     createLinkText : 'Please enter the URL for the link:',
70     /**
71      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
72      */
73     defaultLinkValue : 'http:/'+'/',
74    
75     
76       /**
77      * @cfg {Array} fontFamilies An array of available font families
78      */
79     fontFamilies : [
80         'Arial',
81         'Courier New',
82         'Tahoma',
83         'Times New Roman',
84         'Verdana'
85     ],
86     
87     specialChars : [
88            "©",
89           "®",     
90           "™",    
91           "£" ,    
92          // "—",    
93           "…",    
94           "÷" ,    
95         //  "á" ,     ?? a acute?
96            "€"    , //Euro
97        //   "“"    ,
98         //  "”"    ,
99         //  "•"    ,
100           "°"  //   , // degrees
101
102          // "é"     , // e ecute
103          // "ú"     , // u ecute?
104     ],
105     
106     specialElements : [
107         {
108             text: "Insert Table",
109             xtype: 'MenuItem',
110             xns : Roo.Menu,
111             ihtml :  '<table><tr><td>Cell</td></tr></table>' 
112                 
113         },
114         {    
115             text: "Insert Image",
116             xtype: 'MenuItem',
117             xns : Roo.Menu,
118             ihtml : '<img src="about:blank"/>'
119             
120         }
121         
122          
123     ],
124     
125     
126     inputElements : [ 
127             "form", "input:text", "input:hidden", "input:checkbox", "input:radio", "input:password", 
128             "input:submit", "input:button", "select", "textarea", "label" ],
129     formats : [
130         ["p"] ,  
131         ["h1"],["h2"],["h3"],["h4"],["h5"],["h6"], 
132         ["pre"],[ "code"], 
133         ["abbr"],[ "acronym"],[ "address"],[ "cite"],[ "samp"],[ "var"],
134         ['div'],['span'],
135         ['sup'],['sub']
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.removeAttribute('class');
438                     });
439                     editorcore.cleanWord();
440                     editorcore.syncValue();
441                 },
442                 tabIndex:-1
443             });
444             
445              cmenu.menu.items.push({
446                 actiontype : 'tidy',
447                 html: 'Tidy HTML Source',
448                 handler: function(a,b) {
449                     new Roo.htmleditor.Tidy(editorcore.doc.body);
450                     editorcore.syncValue();
451                 },
452                 tabIndex:-1
453             });
454             
455             
456             tb.add(cmenu);
457         }
458          
459         if (!this.disable.specialElements) {
460             var semenu = {
461                 text: "Other;",
462                 cls: 'x-edit-none',
463                 menu : {
464                     items : []
465                 }
466             };
467             for (var i =0; i < this.specialElements.length; i++) {
468                 semenu.menu.items.push(
469                     Roo.apply({ 
470                         handler: function(a,b) {
471                             editor.insertAtCursor(this.ihtml);
472                         }
473                     }, this.specialElements[i])
474                 );
475                     
476             }
477             
478             tb.add(semenu);
479             
480             
481         }
482          
483         
484         if (this.btns) {
485             for(var i =0; i< this.btns.length;i++) {
486                 var b = Roo.factory(this.btns[i],this.btns[i].xns || Roo.form);
487                 b.cls =  'x-edit-none';
488                 
489                 if(typeof(this.btns[i].cls) != 'undefined' && this.btns[i].cls.indexOf('x-init-enable') !== -1){
490                     b.cls += ' x-init-enable';
491                 }
492                 
493                 b.scope = editorcore;
494                 tb.add(b);
495             }
496         
497         }
498         
499         
500         
501         // disable everything...
502         
503         this.tb.items.each(function(item){
504             
505            if(
506                 item.id != editorcore.frameId+ '-sourceedit' && 
507                 (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)
508             ){
509                 
510                 item.disable();
511             }
512         });
513         this.rendered = true;
514         
515         // the all the btns;
516         editor.on('editorevent', this.updateToolbar, this);
517         // other toolbars need to implement this..
518         //editor.on('editmodechange', this.updateToolbar, this);
519     },
520     
521     
522     relayBtnCmd : function(btn) {
523         this.editorcore.relayCmd(btn.cmd);
524     },
525     // private used internally
526     createLink : function(){
527         //Roo.log("create link?");
528         var ec = this.editorcore;
529         var ar = ec.getAllAncestors();
530         var n = false;
531         for(var i = 0;i< ar.length;i++) {
532             if (ar[i] && ar[i].nodeName == 'A') {
533                 n = ar[i];
534                 break;
535             }
536         }
537         
538         (function() {
539             
540             Roo.MessageBox.show({
541                 title : "Add / Edit Link URL",
542                 msg : "Enter the url for the link",
543                 buttons: Roo.MessageBox.OKCANCEL,
544                 fn: function(btn, url){
545                     if (btn != 'ok') {
546                         return;
547                     }
548                     if(url && url != 'http:/'+'/'){
549                         if (n) {
550                             n.setAttribute('href', url);
551                         } else {
552                             ec.relayCmd('createlink', url);
553                         }
554                     }
555                 },
556                 minWidth:250,
557                 prompt:true,
558                 //multiline: multiline,
559                 modal : true,
560                 value :  n  ? n.getAttribute('href') : '' 
561             });
562             
563              
564         }).defer(100, this); // we have to defer this , otherwise the mouse click gives focus to the main window.
565         
566     },
567
568     
569     /**
570      * Protected method that will not generally be called directly. It triggers
571      * a toolbar update by reading the markup state of the current selection in the editor.
572      */
573     updateToolbar: function(){
574
575         if(!this.editorcore.activated){
576             this.editor.onFirstFocus();
577             return;
578         }
579
580         var btns = this.tb.items.map, 
581             doc = this.editorcore.doc,
582             frameId = this.editorcore.frameId;
583
584         if(!this.disable.font && !Roo.isSafari){
585             /*
586             var name = (doc.queryCommandValue('FontName')||this.editor.defaultFont).toLowerCase();
587             if(name != this.fontSelect.dom.value){
588                 this.fontSelect.dom.value = name;
589             }
590             */
591         }
592         if(!this.disable.format){
593             btns[frameId + '-bold'].toggle(doc.queryCommandState('bold'));
594             btns[frameId + '-italic'].toggle(doc.queryCommandState('italic'));
595             btns[frameId + '-underline'].toggle(doc.queryCommandState('underline'));
596             btns[frameId + '-strikethrough'].toggle(doc.queryCommandState('strikethrough'));
597         }
598         if(!this.disable.alignments){
599             btns[frameId + '-justifyleft'].toggle(doc.queryCommandState('justifyleft'));
600             btns[frameId + '-justifycenter'].toggle(doc.queryCommandState('justifycenter'));
601             btns[frameId + '-justifyright'].toggle(doc.queryCommandState('justifyright'));
602         }
603         if(!Roo.isSafari && !this.disable.lists){
604             btns[frameId + '-insertorderedlist'].toggle(doc.queryCommandState('insertorderedlist'));
605             btns[frameId + '-insertunorderedlist'].toggle(doc.queryCommandState('insertunorderedlist'));
606         }
607         
608         var ans = this.editorcore.getAllAncestors();
609         if (this.formatCombo) {
610             
611             
612             var store = this.formatCombo.store;
613             this.formatCombo.setValue("");
614             for (var i =0; i < ans.length;i++) {
615                 if (ans[i] && store.query('tag',ans[i].tagName.toLowerCase(), false).length) {
616                     // select it..
617                     this.formatCombo.setValue(ans[i].tagName.toLowerCase());
618                     break;
619                 }
620             }
621         }
622         
623         
624         
625         // hides menus... - so this cant be on a menu...
626         Roo.menu.MenuMgr.hideAll();
627
628         //this.editorsyncValue();
629     },
630    
631     
632     createFontOptions : function(){
633         var buf = [], fs = this.fontFamilies, ff, lc;
634         
635         
636         
637         for(var i = 0, len = fs.length; i< len; i++){
638             ff = fs[i];
639             lc = ff.toLowerCase();
640             buf.push(
641                 '<option value="',lc,'" style="font-family:',ff,';"',
642                     (this.defaultFont == lc ? ' selected="true">' : '>'),
643                     ff,
644                 '</option>'
645             );
646         }
647         return buf.join('');
648     },
649     
650     toggleSourceEdit : function(sourceEditMode){
651         
652         Roo.log("toolbar toogle");
653         if(sourceEditMode === undefined){
654             sourceEditMode = !this.sourceEditMode;
655         }
656         this.sourceEditMode = sourceEditMode === true;
657         var btn = this.tb.items.get(this.editorcore.frameId +'-sourceedit');
658         // just toggle the button?
659         if(btn.pressed !== this.sourceEditMode){
660             btn.toggle(this.sourceEditMode);
661             return;
662         }
663         
664         if(sourceEditMode){
665             Roo.log("disabling buttons");
666             this.tb.items.each(function(item){
667                 if(item.cmd != 'sourceedit' && (typeof(item.cls) != 'undefined' && item.cls.indexOf('x-init-enable') === -1)){
668                     item.disable();
669                 }
670             });
671           
672         }else{
673             Roo.log("enabling buttons");
674             if(this.editorcore.initialized){
675                 this.tb.items.each(function(item){
676                     item.enable();
677                 });
678                 // initialize 'blocks'
679                 Roo.each(Roo.get(this.editorcore.doc.body).query('*[data-block]'), function(e) {
680                     Roo.htmleditor.Block.factory(e).updateElement(e);
681                 },this);
682             
683             }
684             
685         }
686         Roo.log("calling toggole on editor");
687         // tell the editor that it's been pressed..
688         this.editor.toggleSourceEdit(sourceEditMode);
689        
690     },
691      /**
692      * Object collection of toolbar tooltips for the buttons in the editor. The key
693      * is the command id associated with that button and the value is a valid QuickTips object.
694      * For example:
695 <pre><code>
696 {
697     bold : {
698         title: 'Bold (Ctrl+B)',
699         text: 'Make the selected text bold.',
700         cls: 'x-html-editor-tip'
701     },
702     italic : {
703         title: 'Italic (Ctrl+I)',
704         text: 'Make the selected text italic.',
705         cls: 'x-html-editor-tip'
706     },
707     ...
708 </code></pre>
709     * @type Object
710      */
711     buttonTips : {
712         bold : {
713             title: 'Bold (Ctrl+B)',
714             text: 'Make the selected text bold.',
715             cls: 'x-html-editor-tip'
716         },
717         italic : {
718             title: 'Italic (Ctrl+I)',
719             text: 'Make the selected text italic.',
720             cls: 'x-html-editor-tip'
721         },
722         underline : {
723             title: 'Underline (Ctrl+U)',
724             text: 'Underline the selected text.',
725             cls: 'x-html-editor-tip'
726         },
727         strikethrough : {
728             title: 'Strikethrough',
729             text: 'Strikethrough the selected text.',
730             cls: 'x-html-editor-tip'
731         },
732         increasefontsize : {
733             title: 'Grow Text',
734             text: 'Increase the font size.',
735             cls: 'x-html-editor-tip'
736         },
737         decreasefontsize : {
738             title: 'Shrink Text',
739             text: 'Decrease the font size.',
740             cls: 'x-html-editor-tip'
741         },
742         backcolor : {
743             title: 'Text Highlight Color',
744             text: 'Change the background color of the selected text.',
745             cls: 'x-html-editor-tip'
746         },
747         forecolor : {
748             title: 'Font Color',
749             text: 'Change the color of the selected text.',
750             cls: 'x-html-editor-tip'
751         },
752         justifyleft : {
753             title: 'Align Text Left',
754             text: 'Align text to the left.',
755             cls: 'x-html-editor-tip'
756         },
757         justifycenter : {
758             title: 'Center Text',
759             text: 'Center text in the editor.',
760             cls: 'x-html-editor-tip'
761         },
762         justifyright : {
763             title: 'Align Text Right',
764             text: 'Align text to the right.',
765             cls: 'x-html-editor-tip'
766         },
767         insertunorderedlist : {
768             title: 'Bullet List',
769             text: 'Start a bulleted list.',
770             cls: 'x-html-editor-tip'
771         },
772         insertorderedlist : {
773             title: 'Numbered List',
774             text: 'Start a numbered list.',
775             cls: 'x-html-editor-tip'
776         },
777         createlink : {
778             title: 'Hyperlink',
779             text: 'Make the selected text a hyperlink.',
780             cls: 'x-html-editor-tip'
781         },
782         sourceedit : {
783             title: 'Source Edit',
784             text: 'Switch to source editing mode.',
785             cls: 'x-html-editor-tip'
786         }
787     },
788     // private
789     onDestroy : function(){
790         if(this.rendered){
791             
792             this.tb.items.each(function(item){
793                 if(item.menu){
794                     item.menu.removeAll();
795                     if(item.menu.el){
796                         item.menu.el.destroy();
797                     }
798                 }
799                 item.destroy();
800             });
801              
802         }
803     },
804     onFirstFocus: function() {
805         this.tb.items.each(function(item){
806            item.enable();
807         });
808     }
809 };
810
811
812
813