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