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