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