Roo/form/HtmlEditor/ToolbarContext.js
[roojs1] / Roo / form / HtmlEditor / ToolbarContext.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 /**
12  * @class Roo.form.HtmlEditor.ToolbarContext
13  * Context Toolbar
14  * 
15  * Usage:
16  *
17  new Roo.form.HtmlEditor({
18     ....
19     toolbars : [
20         { xtype: 'ToolbarStandard', styles : {} }
21         { xtype: 'ToolbarContext', disable : {} }
22     ]
23 })
24
25      
26  * 
27  * @config : {Object} disable List of elements to disable.. (not done yet.)
28  * @config : {Object} styles  Map of styles available.
29  * 
30  */
31
32 Roo.form.HtmlEditor.ToolbarContext = function(config)
33 {
34     
35     Roo.apply(this, config);
36     //Roo.form.HtmlEditorToolbar1.superclass.constructor.call(this, editor.wrap.dom.firstChild, [], config);
37     // dont call parent... till later.
38     this.styles = this.styles || {};
39 }
40
41  
42
43 Roo.form.HtmlEditor.ToolbarContext.types = {
44     'IMG' : {
45         width : {
46             title: "Width",
47             width: 40
48         },
49         height:  {
50             title: "Height",
51             width: 40
52         },
53         align: {
54             title: "Align",
55             opts : [ [""],[ "left"],[ "right"],[ "center"],[ "top"]],
56             width : 80
57             
58         },
59         border: {
60             title: "Border",
61             width: 40
62         },
63         alt: {
64             title: "Alt",
65             width: 120
66         },
67         src : {
68             title: "Src",
69             width: 220
70         }
71         
72     },
73     'A' : {
74         name : {
75             title: "Name",
76             width: 50
77         },
78         href:  {
79             title: "Href",
80             width: 220
81         } // border?
82         
83     },
84     'TABLE' : {
85         rows : {
86             title: "Rows",
87             width: 20
88         },
89         cols : {
90             title: "Cols",
91             width: 20
92         },
93         width : {
94             title: "Width",
95             width: 40
96         },
97         height : {
98             title: "Height",
99             width: 40
100         },
101         border : {
102             title: "Border",
103             width: 20
104         }
105     },
106     'TD' : {
107         width : {
108             title: "Width",
109             width: 40
110         },
111         height : {
112             title: "Height",
113             width: 40
114         },   
115         align: {
116             title: "Align",
117             opts : [[""],[ "left"],[ "center"],[ "right"],[ "justify"],[ "char"]],
118             width: 80
119         },
120         valign: {
121             title: "Valign",
122             opts : [[""],[ "top"],[ "middle"],[ "bottom"],[ "baseline"]],
123             width: 80
124         },
125         colspan: {
126             title: "Colspan",
127             width: 20
128             
129         },
130          'font-family'  : {
131             title : "Font",
132             style : 'fontFamily',
133             displayField: 'display',
134             optname : 'font-family',
135             width: 140
136         }
137     },
138     'INPUT' : {
139         name : {
140             title: "name",
141             width: 120
142         },
143         value : {
144             title: "Value",
145             width: 120
146         },
147         width : {
148             title: "Width",
149             width: 40
150         }
151     },
152     'LABEL' : {
153         'for' : {
154             title: "For",
155             width: 120
156         }
157     },
158     'TEXTAREA' : {
159           name : {
160             title: "name",
161             width: 120
162         },
163         rows : {
164             title: "Rows",
165             width: 20
166         },
167         cols : {
168             title: "Cols",
169             width: 20
170         }
171     },
172     'SELECT' : {
173         name : {
174             title: "name",
175             width: 120
176         },
177         selectoptions : {
178             title: "Options",
179             width: 200
180         }
181     },
182     
183     // should we really allow this??
184     // should this just be 
185     'BODY' : {
186         title : {
187             title: "Title",
188             width: 200,
189             disabled : true
190         }
191     },
192     'SPAN' : {
193         'font-family'  : {
194             title : "Font",
195             style : 'fontFamily',
196             displayField: 'display',
197             optname : 'font-family',
198             width: 140
199         }
200     },
201     'DIV' : {
202         'font-family'  : {
203             title : "Font",
204             style : 'fontFamily',
205             displayField: 'display',
206             optname : 'font-family',
207             width: 140
208         }
209     },
210      'P' : {
211         'font-family'  : {
212             title : "Font",
213             style : 'fontFamily',
214             displayField: 'display',
215             optname : 'font-family',
216             width: 140
217         }
218     },
219     
220     '*' : {
221         // empty..
222     }
223
224 };
225
226 // this should be configurable.. - you can either set it up using stores, or modify options somehwere..
227 Roo.form.HtmlEditor.ToolbarContext.stores = false;
228
229 Roo.form.HtmlEditor.ToolbarContext.options = {
230         'font-family'  : [ 
231                 [ 'Helvetica,Arial,sans-serif', 'Helvetica'],
232                 [ 'Courier New', 'Courier New'],
233                 [ 'Tahoma', 'Tahoma'],
234                 [ 'Times New Roman,serif', 'Times'],
235                 [ 'Verdana','Verdana' ]
236         ]
237 };
238
239 // fixme - these need to be configurable..
240  
241
242 Roo.form.HtmlEditor.ToolbarContext.types
243
244
245 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
246     
247     tb: false,
248     
249     rendered: false,
250     
251     editor : false,
252     /**
253      * @cfg {Object} disable  List of toolbar elements to disable
254          
255      */
256     disable : false,
257     /**
258      * @cfg {Object} styles List of styles 
259      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
260      *
261      * These must be defined in the page, so they get rendered correctly..
262      * .headline { }
263      * TD.underline { }
264      * 
265      */
266     styles : false,
267     
268     options: false,
269     
270     toolbars : false,
271     
272     init : function(editor)
273     {
274         this.editor = editor;
275         
276         
277         var fid = editor.frameId;
278         var etb = this;
279         function btn(id, toggle, handler){
280             var xid = fid + '-'+ id ;
281             return {
282                 id : xid,
283                 cmd : id,
284                 cls : 'x-btn-icon x-edit-'+id,
285                 enableToggle:toggle !== false,
286                 scope: editor, // was editor...
287                 handler:handler||editor.relayBtnCmd,
288                 clickEvent:'mousedown',
289                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
290                 tabIndex:-1
291             };
292         }
293         // create a new element.
294         var wdiv = editor.wrap.createChild({
295                 tag: 'div'
296             }, editor.wrap.dom.firstChild.nextSibling, true);
297         
298         // can we do this more than once??
299         
300          // stop form submits
301       
302  
303         // disable everything...
304         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
305         this.toolbars = {};
306            
307         for (var i in  ty) {
308           
309             this.toolbars[i] = this.buildToolbar(ty[i],i);
310         }
311         this.tb = this.toolbars.BODY;
312         this.tb.el.show();
313         this.buildFooter();
314         this.footer.show();
315         editor.on('hide', function( ) { this.footer.hide() }, this);
316         editor.on('show', function( ) { this.footer.show() }, this);
317         
318          
319         this.rendered = true;
320         
321         // the all the btns;
322         editor.on('editorevent', this.updateToolbar, this);
323         // other toolbars need to implement this..
324         //editor.on('editmodechange', this.updateToolbar, this);
325     },
326     
327     
328     
329     /**
330      * Protected method that will not generally be called directly. It triggers
331      * a toolbar update by reading the markup state of the current selection in the editor.
332      */
333     updateToolbar: function(editor,ev,sel){
334
335         //Roo.log(ev);
336         // capture mouse up - this is handy for selecting images..
337         // perhaps should go somewhere else...
338         if(!this.editor.activated){
339              this.editor.onFirstFocus();
340             return;
341         }
342         
343         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
344         // selectNode - might want to handle IE?
345         if (ev &&
346             (ev.type == 'mouseup' || ev.type == 'click' ) &&
347             ev.target && ev.target.tagName == 'IMG') {
348             // they have click on an image...
349             // let's see if we can change the selection...
350             sel = ev.target;
351          
352               var nodeRange = sel.ownerDocument.createRange();
353             try {
354                 nodeRange.selectNode(sel);
355             } catch (e) {
356                 nodeRange.selectNodeContents(sel);
357             }
358             //nodeRange.collapse(true);
359             var s = editor.win.getSelection();
360             s.removeAllRanges();
361             s.addRange(nodeRange);
362         }  
363         
364       
365         var updateFooter = sel ? false : true;
366         
367         
368         var ans = this.editor.getAllAncestors();
369         
370         // pick
371         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
372         
373         if (!sel) { 
374             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editor.doc.body;
375             sel = sel ? sel : this.editor.doc.body;
376             sel = sel.tagName.length ? sel : this.editor.doc.body;
377             
378         }
379         // pick a menu that exists..
380         var tn = sel.tagName.toUpperCase();
381         //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
382         
383         tn = sel.tagName.toUpperCase();
384         
385         var lastSel = this.tb.selectedNode
386         
387         this.tb.selectedNode = sel;
388         
389         // if current menu does not match..
390         if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode)) {
391                 
392             this.tb.el.hide();
393             ///console.log("show: " + tn);
394             this.tb =  typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
395             this.tb.el.show();
396             // update name
397             this.tb.items.first().el.innerHTML = tn + ':&nbsp;';
398             
399             
400             // update attributes
401             if (this.tb.fields) {
402                 this.tb.fields.each(function(e) {
403                     if (e.stylename) {
404                         e.setValue(sel.style[e.stylename]);
405                         return;
406                     } 
407                    e.setValue(sel.getAttribute(e.attrname));
408                 });
409             }
410             
411             var hasStyles = false;
412             for(var i in this.styles) {
413                 hasStyles = true;
414                 break;
415             }
416             
417             // update styles
418             if (hasStyles) { 
419                 var st = this.tb.fields.item(0);
420                 
421                 st.store.removeAll();
422                
423                 
424                 var cn = sel.className.split(/\s+/);
425                 
426                 var avs = [];
427                 if (this.styles['*']) {
428                     
429                     Roo.each(this.styles['*'], function(v) {
430                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
431                     });
432                 }
433                 if (this.styles[tn]) { 
434                     Roo.each(this.styles[tn], function(v) {
435                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
436                     });
437                 }
438                 
439                 st.store.loadData(avs);
440                 st.collapse();
441                 st.setValue(cn);
442             }
443             // flag our selected Node.
444             this.tb.selectedNode = sel;
445            
446            
447             Roo.menu.MenuMgr.hideAll();
448
449         }
450         
451         if (!updateFooter) {
452             //this.footDisp.dom.innerHTML = ''; 
453             return;
454         }
455         // update the footer
456         //
457         var html = '';
458         
459         this.footerEls = ans.reverse();
460         Roo.each(this.footerEls, function(a,i) {
461             if (!a) { return; }
462             html += html.length ? ' &gt; '  :  '';
463             
464             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
465             
466         });
467        
468         // 
469         var sz = this.footDisp.up('td').getSize();
470         this.footDisp.dom.style.width = (sz.width -10) + 'px';
471         this.footDisp.dom.style.marginLeft = '5px';
472         
473         this.footDisp.dom.style.overflow = 'hidden';
474         
475         this.footDisp.dom.innerHTML = html;
476             
477         //this.editorsyncValue();
478     },
479      
480     
481    
482        
483     // private
484     onDestroy : function(){
485         if(this.rendered){
486             
487             this.tb.items.each(function(item){
488                 if(item.menu){
489                     item.menu.removeAll();
490                     if(item.menu.el){
491                         item.menu.el.destroy();
492                     }
493                 }
494                 item.destroy();
495             });
496              
497         }
498     },
499     onFirstFocus: function() {
500         // need to do this for all the toolbars..
501         this.tb.items.each(function(item){
502            item.enable();
503         });
504     },
505     buildToolbar: function(tlist, nm)
506     {
507         var editor = this.editor;
508          // create a new element.
509         var wdiv = editor.wrap.createChild({
510                 tag: 'div'
511             }, editor.wrap.dom.firstChild.nextSibling, true);
512         
513        
514         var tb = new Roo.Toolbar(wdiv);
515         // add the name..
516         
517         tb.add(nm+ ":&nbsp;");
518         
519         var styles = [];
520         for(var i in this.styles) {
521             styles.push(i);
522         }
523         
524         // styles...
525         if (styles && styles.length) {
526             
527             // this needs a multi-select checkbox...
528             tb.addField( new Roo.form.ComboBox({
529                 store: new Roo.data.SimpleStore({
530                     id : 'val',
531                     fields: ['val', 'selected'],
532                     data : [] 
533                 }),
534                 name : '-roo-edit-className',
535                 attrname : 'className',
536                 displayField: 'val',
537                 typeAhead: false,
538                 mode: 'local',
539                 editable : false,
540                 triggerAction: 'all',
541                 emptyText:'Select Style',
542                 selectOnFocus:true,
543                 width: 130,
544                 listeners : {
545                     'select': function(c, r, i) {
546                         // initial support only for on class per el..
547                         tb.selectedNode.className =  r ? r.get('val') : '';
548                         editor.syncValue();
549                     }
550                 }
551     
552             }));
553         }
554         
555         var tbc = Roo.form.HtmlEditor.ToolbarContext;
556         var tbops = tbc.options;
557         
558         for (var i in tlist) {
559             
560             var item = tlist[i];
561             tb.add(item.title + ":&nbsp;");
562             
563             
564             //optname == used so you can configure the options available..
565             var opts = item.opts ? item.opts : false;
566             if (item.optname) {
567                 opts = tbops[item.optname];
568            
569             }
570             
571             if (opts) {
572                 // opts == pulldown..
573                 tb.addField( new Roo.form.ComboBox({
574                     store:   typeof(tbc.stores[i]) != 'undefined' ?  tbc.stores[i] : new Roo.data.SimpleStore({
575                         id : 'val',
576                         fields: ['val', 'display'],
577                         data : opts  
578                     }),
579                     name : '-roo-edit-' + i,
580                     attrname : i,
581                     stylename : item.style ? item.style : false,
582                     displayField: item.displayField ? item.displayField : 'val',
583                     valueField :  'val',
584                     typeAhead: false,
585                     mode: 'local',
586                     editable : false,
587                     triggerAction: 'all',
588                     emptyText:'Select',
589                     selectOnFocus:true,
590                     width: item.width ? item.width  : 130,
591                     listeners : {
592                         'select': function(c, r, i) {
593                             if (c.stylename) {
594                                 tb.selectedNode.style[c.stylename] =  r.get('val');
595                                 return;
596                             }
597                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
598                         }
599                     }
600
601                 }));
602                 continue;
603                     
604                  
605                 
606                 tb.addField( new Roo.form.TextField({
607                     name: i,
608                     width: 100,
609                     //allowBlank:false,
610                     value: ''
611                 }));
612                 continue;
613             }
614             tb.addField( new Roo.form.TextField({
615                 name: '-roo-edit-' + i,
616                 attrname : i,
617                 
618                 width: item.width,
619                 //allowBlank:true,
620                 value: '',
621                 listeners: {
622                     'change' : function(f, nv, ov) {
623                         tb.selectedNode.setAttribute(f.attrname, nv);
624                     }
625                 }
626             }));
627              
628         }
629         tb.addFill();
630         var _this = this;
631         tb.addButton( {
632             text: 'Remove Tag',
633     
634             listeners : {
635                 click : function ()
636                 {
637                     // remove
638                     // undo does not work.
639                      
640                     var sn = tb.selectedNode;
641                     
642                     var pn = sn.parentNode;
643                     
644                     var stn =  sn.childNodes[0];
645                     var en = sn.childNodes[sn.childNodes.length - 1 ];
646                     while (sn.childNodes.length) {
647                         var node = sn.childNodes[0];
648                         sn.removeChild(node);
649                         //Roo.log(node);
650                         pn.insertBefore(node, sn);
651                         
652                     }
653                     pn.removeChild(sn);
654                     var range = editor.createRange();
655         
656                     range.setStart(stn,0);
657                     range.setEnd(en,0); //????
658                     //range.selectNode(sel);
659                     
660                     
661                     var selection = editor.getSelection();
662                     selection.removeAllRanges();
663                     selection.addRange(range);
664                     
665                     
666                     
667                     //_this.updateToolbar(null, null, pn);
668                     _this.updateToolbar(null, null, null);
669                     _this.footDisp.dom.innerHTML = ''; 
670                 }
671             }
672             
673                     
674                 
675             
676         });
677         
678         
679         tb.el.on('click', function(e){
680             e.preventDefault(); // what does this do?
681         });
682         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
683         tb.el.hide();
684         tb.name = nm;
685         // dont need to disable them... as they will get hidden
686         return tb;
687          
688         
689     },
690     buildFooter : function()
691     {
692         
693         var fel = this.editor.wrap.createChild();
694         this.footer = new Roo.Toolbar(fel);
695         // toolbar has scrolly on left / right?
696         var footDisp= new Roo.Toolbar.Fill();
697         var _t = this;
698         this.footer.add(
699             {
700                 text : '&lt;',
701                 xtype: 'Button',
702                 handler : function() {
703                     _t.footDisp.scrollTo('left',0,true)
704                 }
705             }
706         );
707         this.footer.add( footDisp );
708         this.footer.add( 
709             {
710                 text : '&gt;',
711                 xtype: 'Button',
712                 handler : function() {
713                     // no animation..
714                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
715                 }
716             }
717         );
718         var fel = Roo.get(footDisp.el);
719         fel.addClass('x-editor-context');
720         this.footDispWrap = fel; 
721         this.footDispWrap.overflow  = 'hidden';
722         
723         this.footDisp = fel.createChild();
724         this.footDispWrap.on('click', this.onContextClick, this)
725         
726         
727     },
728     onContextClick : function (ev,dom)
729     {
730         ev.preventDefault();
731         var  cn = dom.className;
732         //Roo.log(cn);
733         if (!cn.match(/x-ed-loc-/)) {
734             return;
735         }
736         var n = cn.split('-').pop();
737         var ans = this.footerEls;
738         var sel = ans[n];
739         
740          // pick
741         var range = this.editor.createRange();
742         
743         range.selectNodeContents(sel);
744         //range.selectNode(sel);
745         
746         
747         var selection = this.editor.getSelection();
748         selection.removeAllRanges();
749         selection.addRange(range);
750         
751         
752         
753         this.updateToolbar(null, null, sel);
754         
755         
756     }
757     
758     
759     
760     
761     
762 });
763
764
765
766
767