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