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         Roo.log('HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!111');
276         Roo.log(this);
277         
278         var fid = editor.frameId;
279         var etb = this;
280         function btn(id, toggle, handler){
281             var xid = fid + '-'+ id ;
282             return {
283                 id : xid,
284                 cmd : id,
285                 cls : 'x-btn-icon x-edit-'+id,
286                 enableToggle:toggle !== false,
287                 scope: editor, // was editor...
288                 handler:handler||editor.relayBtnCmd,
289                 clickEvent:'mousedown',
290                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
291                 tabIndex:-1
292             };
293         }
294         // create a new element.
295         var wdiv = editor.wrap.createChild({
296                 tag: 'div'
297             }, editor.wrap.dom.firstChild.nextSibling, true);
298         
299         // can we do this more than once??
300         
301          // stop form submits
302       
303  
304         // disable everything...
305         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
306         this.toolbars = {};
307            
308         for (var i in  ty) {
309           
310             this.toolbars[i] = this.buildToolbar(ty[i],i);
311         }
312         this.tb = this.toolbars.BODY;
313         this.tb.el.show();
314         this.buildFooter();
315         this.footer.show();
316         editor.on('hide', function( ) { this.footer.hide() }, this);
317         editor.on('show', function( ) { this.footer.show() }, this);
318         
319          
320         this.rendered = true;
321         
322         // the all the btns;
323         editor.on('editorevent', this.updateToolbar, this);
324         // other toolbars need to implement this..
325         //editor.on('editmodechange', this.updateToolbar, this);
326     },
327     
328     
329     
330     /**
331      * Protected method that will not generally be called directly. It triggers
332      * a toolbar update by reading the markup state of the current selection in the editor.
333      */
334     updateToolbar: function(editor,ev,sel){
335
336         //Roo.log(ev);
337         // capture mouse up - this is handy for selecting images..
338         // perhaps should go somewhere else...
339         if(!this.editor.activated){
340              this.editor.onFirstFocus();
341             return;
342         }
343         
344         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
345         // selectNode - might want to handle IE?
346         if (ev &&
347             (ev.type == 'mouseup' || ev.type == 'click' ) &&
348             ev.target && ev.target.tagName == 'IMG') {
349             // they have click on an image...
350             // let's see if we can change the selection...
351             sel = ev.target;
352          
353               var nodeRange = sel.ownerDocument.createRange();
354             try {
355                 nodeRange.selectNode(sel);
356             } catch (e) {
357                 nodeRange.selectNodeContents(sel);
358             }
359             //nodeRange.collapse(true);
360             var s = editor.win.getSelection();
361             s.removeAllRanges();
362             s.addRange(nodeRange);
363         }  
364         
365       
366         var updateFooter = sel ? false : true;
367         
368         
369         var ans = this.editor.getAllAncestors();
370         
371         // pick
372         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
373         
374         if (!sel) { 
375             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editor.doc.body;
376             sel = sel ? sel : this.editor.doc.body;
377             sel = sel.tagName.length ? sel : this.editor.doc.body;
378             
379         }
380         // pick a menu that exists..
381         var tn = sel.tagName.toUpperCase();
382         //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
383         
384         tn = sel.tagName.toUpperCase();
385         
386         var lastSel = this.tb.selectedNode
387         
388         this.tb.selectedNode = sel;
389         
390         // if current menu does not match..
391         if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode)) {
392                 
393             this.tb.el.hide();
394             ///console.log("show: " + tn);
395             this.tb =  typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
396             this.tb.el.show();
397             // update name
398             this.tb.items.first().el.innerHTML = tn + ':&nbsp;';
399             
400             
401             // update attributes
402             if (this.tb.fields) {
403                 this.tb.fields.each(function(e) {
404                     if (e.stylename) {
405                         e.setValue(sel.style[e.stylename]);
406                         return;
407                     } 
408                    e.setValue(sel.getAttribute(e.attrname));
409                 });
410             }
411             
412             var hasStyles = false;
413             for(var i in this.styles) {
414                 hasStyles = true;
415                 break;
416             }
417             
418             // update styles
419             if (hasStyles) { 
420                 var st = this.tb.fields.item(0);
421                 
422                 st.store.removeAll();
423                
424                 
425                 var cn = sel.className.split(/\s+/);
426                 
427                 var avs = [];
428                 if (this.styles['*']) {
429                     
430                     Roo.each(this.styles['*'], function(v) {
431                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
432                     });
433                 }
434                 if (this.styles[tn]) { 
435                     Roo.each(this.styles[tn], function(v) {
436                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
437                     });
438                 }
439                 
440                 st.store.loadData(avs);
441                 st.collapse();
442                 st.setValue(cn);
443             }
444             // flag our selected Node.
445             this.tb.selectedNode = sel;
446            
447            
448             Roo.menu.MenuMgr.hideAll();
449
450         }
451         
452         if (!updateFooter) {
453             //this.footDisp.dom.innerHTML = ''; 
454             return;
455         }
456         // update the footer
457         //
458         var html = '';
459         
460         this.footerEls = ans.reverse();
461         Roo.each(this.footerEls, function(a,i) {
462             if (!a) { return; }
463             html += html.length ? ' &gt; '  :  '';
464             
465             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
466             
467         });
468        
469         // 
470         var sz = this.footDisp.up('td').getSize();
471         this.footDisp.dom.style.width = (sz.width -10) + 'px';
472         this.footDisp.dom.style.marginLeft = '5px';
473         
474         this.footDisp.dom.style.overflow = 'hidden';
475         
476         this.footDisp.dom.innerHTML = html;
477             
478         //this.editorsyncValue();
479     },
480      
481     
482    
483        
484     // private
485     onDestroy : function(){
486         if(this.rendered){
487             
488             this.tb.items.each(function(item){
489                 if(item.menu){
490                     item.menu.removeAll();
491                     if(item.menu.el){
492                         item.menu.el.destroy();
493                     }
494                 }
495                 item.destroy();
496             });
497              
498         }
499     },
500     onFirstFocus: function() {
501         // need to do this for all the toolbars..
502         this.tb.items.each(function(item){
503            item.enable();
504         });
505     },
506     buildToolbar: function(tlist, nm)
507     {
508         var editor = this.editor;
509          // create a new element.
510         var wdiv = editor.wrap.createChild({
511                 tag: 'div'
512             }, editor.wrap.dom.firstChild.nextSibling, true);
513         
514        
515         var tb = new Roo.Toolbar(wdiv);
516         // add the name..
517         
518         tb.add(nm+ ":&nbsp;");
519         
520         var styles = [];
521         for(var i in this.styles) {
522             styles.push(i);
523         }
524         
525         // styles...
526         if (styles && styles.length) {
527             
528             // this needs a multi-select checkbox...
529             tb.addField( new Roo.form.ComboBox({
530                 store: new Roo.data.SimpleStore({
531                     id : 'val',
532                     fields: ['val', 'selected'],
533                     data : [] 
534                 }),
535                 name : '-roo-edit-className',
536                 attrname : 'className',
537                 displayField: 'val',
538                 typeAhead: false,
539                 mode: 'local',
540                 editable : false,
541                 triggerAction: 'all',
542                 emptyText:'Select Style',
543                 selectOnFocus:true,
544                 width: 130,
545                 listeners : {
546                     'select': function(c, r, i) {
547                         // initial support only for on class per el..
548                         tb.selectedNode.className =  r ? r.get('val') : '';
549                         editor.syncValue();
550                     }
551                 }
552     
553             }));
554         }
555         
556         var tbc = Roo.form.HtmlEditor.ToolbarContext;
557         var tbops = tbc.options;
558         
559         for (var i in tlist) {
560             
561             var item = tlist[i];
562             tb.add(item.title + ":&nbsp;");
563             
564             
565             //optname == used so you can configure the options available..
566             var opts = item.opts ? item.opts : false;
567             if (item.optname) {
568                 opts = tbops[item.optname];
569            
570             }
571             
572             if (opts) {
573                 // opts == pulldown..
574                 tb.addField( new Roo.form.ComboBox({
575                     store:   typeof(tbc.stores[i]) != 'undefined' ?  Roo.factory(tbc.stores[i],Roo.data) : new Roo.data.SimpleStore({
576                         id : 'val',
577                         fields: ['val', 'display'],
578                         data : opts  
579                     }),
580                     name : '-roo-edit-' + i,
581                     attrname : i,
582                     stylename : item.style ? item.style : false,
583                     displayField: item.displayField ? item.displayField : 'val',
584                     valueField :  'val',
585                     typeAhead: false,
586                     mode: typeof(tbc.stores[i]) != 'undefined'  ? 'remote' : 'local',
587                     editable : false,
588                     triggerAction: 'all',
589                     emptyText:'Select',
590                     selectOnFocus:true,
591                     width: item.width ? item.width  : 130,
592                     listeners : {
593                         'select': function(c, r, i) {
594                             if (c.stylename) {
595                                 tb.selectedNode.style[c.stylename] =  r.get('val');
596                                 return;
597                             }
598                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
599                         }
600                     }
601
602                 }));
603                 continue;
604                     
605                  
606                 
607                 tb.addField( new Roo.form.TextField({
608                     name: i,
609                     width: 100,
610                     //allowBlank:false,
611                     value: ''
612                 }));
613                 continue;
614             }
615             tb.addField( new Roo.form.TextField({
616                 name: '-roo-edit-' + i,
617                 attrname : i,
618                 
619                 width: item.width,
620                 //allowBlank:true,
621                 value: '',
622                 listeners: {
623                     'change' : function(f, nv, ov) {
624                         tb.selectedNode.setAttribute(f.attrname, nv);
625                     }
626                 }
627             }));
628              
629         }
630         tb.addFill();
631         var _this = this;
632         tb.addButton( {
633             text: 'Remove Tag',
634     
635             listeners : {
636                 click : function ()
637                 {
638                     // remove
639                     // undo does not work.
640                      
641                     var sn = tb.selectedNode;
642                     
643                     var pn = sn.parentNode;
644                     
645                     var stn =  sn.childNodes[0];
646                     var en = sn.childNodes[sn.childNodes.length - 1 ];
647                     while (sn.childNodes.length) {
648                         var node = sn.childNodes[0];
649                         sn.removeChild(node);
650                         //Roo.log(node);
651                         pn.insertBefore(node, sn);
652                         
653                     }
654                     pn.removeChild(sn);
655                     var range = editor.createRange();
656         
657                     range.setStart(stn,0);
658                     range.setEnd(en,0); //????
659                     //range.selectNode(sel);
660                     
661                     
662                     var selection = editor.getSelection();
663                     selection.removeAllRanges();
664                     selection.addRange(range);
665                     
666                     
667                     
668                     //_this.updateToolbar(null, null, pn);
669                     _this.updateToolbar(null, null, null);
670                     _this.footDisp.dom.innerHTML = ''; 
671                 }
672             }
673             
674                     
675                 
676             
677         });
678         
679         
680         tb.el.on('click', function(e){
681             e.preventDefault(); // what does this do?
682         });
683         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
684         tb.el.hide();
685         tb.name = nm;
686         // dont need to disable them... as they will get hidden
687         return tb;
688          
689         
690     },
691     buildFooter : function()
692     {
693         
694         var fel = this.editor.wrap.createChild();
695         this.footer = new Roo.Toolbar(fel);
696         // toolbar has scrolly on left / right?
697         var footDisp= new Roo.Toolbar.Fill();
698         var _t = this;
699         this.footer.add(
700             {
701                 text : '&lt;',
702                 xtype: 'Button',
703                 handler : function() {
704                     _t.footDisp.scrollTo('left',0,true)
705                 }
706             }
707         );
708         this.footer.add( footDisp );
709         this.footer.add( 
710             {
711                 text : '&gt;',
712                 xtype: 'Button',
713                 handler : function() {
714                     // no animation..
715                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
716                 }
717             }
718         );
719         var fel = Roo.get(footDisp.el);
720         fel.addClass('x-editor-context');
721         this.footDispWrap = fel; 
722         this.footDispWrap.overflow  = 'hidden';
723         
724         this.footDisp = fel.createChild();
725         this.footDispWrap.on('click', this.onContextClick, this)
726         
727         
728     },
729     onContextClick : function (ev,dom)
730     {
731         ev.preventDefault();
732         var  cn = dom.className;
733         //Roo.log(cn);
734         if (!cn.match(/x-ed-loc-/)) {
735             return;
736         }
737         var n = cn.split('-').pop();
738         var ans = this.footerEls;
739         var sel = ans[n];
740         
741          // pick
742         var range = this.editor.createRange();
743         
744         range.selectNodeContents(sel);
745         //range.selectNode(sel);
746         
747         
748         var selection = this.editor.getSelection();
749         selection.removeAllRanges();
750         selection.addRange(range);
751         
752         
753         
754         this.updateToolbar(null, null, sel);
755         
756         
757     }
758     
759     
760     
761     
762     
763 });
764
765
766
767
768