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     opts : [
194         [""],
195         [ 'Arial'],
196         [ 'Courier New'],
197         [ 'Tahoma'],
198         [ 'Times New Roman'],
199         [ 'Verdana' ]
200     ],
201     width: 160
202
203 };
204
205 Roo.each([ 'SPAN', 'DIV' , 'TD' , 'P' ], function(tg) {
206     var cx= Roo.form.HtmlEditor.ToolbarContext;
207     if (typeof(cx.types[tg]) == 'undefined') {
208         cx.types[tg] = {};
209     }
210     
211     cx.types[tg]['font-family'] = cx[ 'font-family'] ;
212 });
213
214 Roo.form.HtmlEditor.ToolbarContext.types
215
216
217 Roo.apply(Roo.form.HtmlEditor.ToolbarContext.prototype,  {
218     
219     tb: false,
220     
221     rendered: false,
222     
223     editor : false,
224     /**
225      * @cfg {Object} disable  List of toolbar elements to disable
226          
227      */
228     disable : false,
229     /**
230      * @cfg {Object} styles List of styles 
231      *    eg. { '*' : [ 'headline' ] , 'TD' : [ 'underline', 'double-underline' ] } 
232      *
233      * These must be defined in the page, so they get rendered correctly..
234      * .headline { }
235      * TD.underline { }
236      * 
237      */
238     styles : false,
239     
240     
241     
242     toolbars : false,
243     
244     init : function(editor)
245     {
246         this.editor = editor;
247         
248         
249         var fid = editor.frameId;
250         var etb = this;
251         function btn(id, toggle, handler){
252             var xid = fid + '-'+ id ;
253             return {
254                 id : xid,
255                 cmd : id,
256                 cls : 'x-btn-icon x-edit-'+id,
257                 enableToggle:toggle !== false,
258                 scope: editor, // was editor...
259                 handler:handler||editor.relayBtnCmd,
260                 clickEvent:'mousedown',
261                 tooltip: etb.buttonTips[id] || undefined, ///tips ???
262                 tabIndex:-1
263             };
264         }
265         // create a new element.
266         var wdiv = editor.wrap.createChild({
267                 tag: 'div'
268             }, editor.wrap.dom.firstChild.nextSibling, true);
269         
270         // can we do this more than once??
271         
272          // stop form submits
273       
274  
275         // disable everything...
276         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
277         this.toolbars = {};
278            
279         for (var i in  ty) {
280           
281             this.toolbars[i] = this.buildToolbar(ty[i],i);
282         }
283         this.tb = this.toolbars.BODY;
284         this.tb.el.show();
285         this.buildFooter();
286         this.footer.show();
287         editor.on('hide', function( ) { this.footer.hide() }, this);
288         editor.on('show', function( ) { this.footer.show() }, this);
289         
290          
291         this.rendered = true;
292         
293         // the all the btns;
294         editor.on('editorevent', this.updateToolbar, this);
295         // other toolbars need to implement this..
296         //editor.on('editmodechange', this.updateToolbar, this);
297     },
298     
299     
300     
301     /**
302      * Protected method that will not generally be called directly. It triggers
303      * a toolbar update by reading the markup state of the current selection in the editor.
304      */
305     updateToolbar: function(editor,ev,sel){
306
307         //Roo.log(ev);
308         // capture mouse up - this is handy for selecting images..
309         // perhaps should go somewhere else...
310         if(!this.editor.activated){
311              this.editor.onFirstFocus();
312             return;
313         }
314         
315         // http://developer.yahoo.com/yui/docs/simple-editor.js.html
316         // selectNode - might want to handle IE?
317         if (ev &&
318             (ev.type == 'mouseup' || ev.type == 'click' ) &&
319             ev.target && ev.target.tagName == 'IMG') {
320             // they have click on an image...
321             // let's see if we can change the selection...
322             sel = ev.target;
323          
324               var nodeRange = sel.ownerDocument.createRange();
325             try {
326                 nodeRange.selectNode(sel);
327             } catch (e) {
328                 nodeRange.selectNodeContents(sel);
329             }
330             //nodeRange.collapse(true);
331             var s = editor.win.getSelection();
332             s.removeAllRanges();
333             s.addRange(nodeRange);
334         }  
335         
336       
337         var updateFooter = sel ? false : true;
338         
339         
340         var ans = this.editor.getAllAncestors();
341         
342         // pick
343         var ty= Roo.form.HtmlEditor.ToolbarContext.types;
344         
345         if (!sel) { 
346             sel = ans.length ? (ans[0] ?  ans[0]  : ans[1]) : this.editor.doc.body;
347             sel = sel ? sel : this.editor.doc.body;
348             sel = sel.tagName.length ? sel : this.editor.doc.body;
349             
350         }
351         // pick a menu that exists..
352         var tn = sel.tagName.toUpperCase();
353         //sel = typeof(ty[tn]) != 'undefined' ? sel : this.editor.doc.body;
354         
355         tn = sel.tagName.toUpperCase();
356         
357         var lastSel = this.tb.selectedNode
358         
359         this.tb.selectedNode = sel;
360         
361         // if current menu does not match..
362         if ((this.tb.name != tn) || (lastSel != this.tb.selectedNode)) {
363                 
364             this.tb.el.hide();
365             ///console.log("show: " + tn);
366             this.tb =  typeof(ty[tn]) != 'undefined' ? this.toolbars[tn] : this.toolbars['*'];
367             this.tb.el.show();
368             // update name
369             this.tb.items.first().el.innerHTML = tn + ':&nbsp;';
370             
371             
372             // update attributes
373             if (this.tb.fields) {
374                 this.tb.fields.each(function(e) {
375                     if (e.stylename) {
376                         e.setValue(sel.style[e.stylename]);
377                     }
378                     
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'],
544                         data : item.opts  
545                     }),
546                     name : '-roo-edit-' + i,
547                     attrname : i,
548                     stylename : item.style ? item.style : false,
549                     displayField:'val',
550                     typeAhead: false,
551                     mode: 'local',
552                     editable : false,
553                     triggerAction: 'all',
554                     emptyText:'Select',
555                     selectOnFocus:true,
556                     width: item.width ? item.width  : 130,
557                     listeners : {
558                         'select': function(c, r, i) {
559                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
560                         }
561                     }
562
563                 }));
564                 continue;
565                     
566                  
567                 
568                 tb.addField( new Roo.form.TextField({
569                     name: i,
570                     width: 100,
571                     //allowBlank:false,
572                     value: ''
573                 }));
574                 continue;
575             }
576             tb.addField( new Roo.form.TextField({
577                 name: '-roo-edit-' + i,
578                 attrname : i,
579                 
580                 width: item.width,
581                 //allowBlank:true,
582                 value: '',
583                 listeners: {
584                     'change' : function(f, nv, ov) {
585                         tb.selectedNode.setAttribute(f.attrname, nv);
586                     }
587                 }
588             }));
589              
590         }
591         tb.addFill();
592         var _this = this;
593         tb.addButton( {
594             text: 'Remove Tag',
595     
596             listeners : {
597                 click : function ()
598                 {
599                     // remove
600                     // undo does not work.
601                      
602                     var sn = tb.selectedNode;
603                     Roo.log(sn);
604                     var pn = sn.parentNode;
605                     
606                     var stn =  sn.childNodes[0];
607                     var en = sn.childNodes[sn.childNodes.length - 1 ];
608                     while (sn.childNodes.length) {
609                         var node = sn.childNodes[0];
610                         sn.removeChild(node);
611                         Roo.log(node);
612                         pn.insertBefore(node, sn);
613                         
614                     }
615                     pn.removeChild(sn);
616                     var range = editor.createRange();
617         
618                     range.setStart(stn,0);
619                     range.setEnd(en,0); //????
620                     //range.selectNode(sel);
621                     
622                     
623                     var selection = editor.getSelection();
624                     selection.removeAllRanges();
625                     selection.addRange(range);
626                     
627                     
628                     
629                     //_this.updateToolbar(null, null, pn);
630                     _this.updateToolbar(null, null, null);
631                     this.footDisp.dom.innerHTML = ''; 
632                 }
633             }
634             
635                     
636                 
637             
638         });
639         
640         
641         tb.el.on('click', function(e){
642             e.preventDefault(); // what does this do?
643         });
644         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
645         tb.el.hide();
646         tb.name = nm;
647         // dont need to disable them... as they will get hidden
648         return tb;
649          
650         
651     },
652     buildFooter : function()
653     {
654         
655         var fel = this.editor.wrap.createChild();
656         this.footer = new Roo.Toolbar(fel);
657         // toolbar has scrolly on left / right?
658         var footDisp= new Roo.Toolbar.Fill();
659         var _t = this;
660         this.footer.add(
661             {
662                 text : '&lt;',
663                 xtype: 'Button',
664                 handler : function() {
665                     _t.footDisp.scrollTo('left',0,true)
666                 }
667             }
668         );
669         this.footer.add( footDisp );
670         this.footer.add( 
671             {
672                 text : '&gt;',
673                 xtype: 'Button',
674                 handler : function() {
675                     // no animation..
676                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
677                 }
678             }
679         );
680         var fel = Roo.get(footDisp.el);
681         fel.addClass('x-editor-context');
682         this.footDispWrap = fel; 
683         this.footDispWrap.overflow  = 'hidden';
684         
685         this.footDisp = fel.createChild();
686         this.footDispWrap.on('click', this.onContextClick, this)
687         
688         
689     },
690     onContextClick : function (ev,dom)
691     {
692         ev.preventDefault();
693         var  cn = dom.className;
694         Roo.log(cn);
695         if (!cn.match(/x-ed-loc-/)) {
696             return;
697         }
698         var n = cn.split('-').pop();
699         var ans = this.footerEls;
700         var sel = ans[n];
701         
702          // pick
703         var range = this.editor.createRange();
704         
705         range.selectNodeContents(sel);
706         //range.selectNode(sel);
707         
708         
709         var selection = this.editor.getSelection();
710         selection.removeAllRanges();
711         selection.addRange(range);
712         
713         
714         
715         this.updateToolbar(null, null, sel);
716         
717         
718     }
719     
720     
721     
722     
723     
724 });
725
726
727
728
729