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