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