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