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