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