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    
422        
423     // private
424     onDestroy : function(){
425         if(this.rendered){
426             
427             this.tb.items.each(function(item){
428                 if(item.menu){
429                     item.menu.removeAll();
430                     if(item.menu.el){
431                         item.menu.el.destroy();
432                     }
433                 }
434                 item.destroy();
435             });
436              
437         }
438     },
439     onFirstFocus: function() {
440         // need to do this for all the toolbars..
441         this.tb.items.each(function(item){
442            item.enable();
443         });
444     },
445     buildToolbar: function(tlist, nm)
446     {
447         var editor = this.editor;
448          // create a new element.
449         var wdiv = editor.wrap.createChild({
450                 tag: 'div'
451             }, editor.wrap.dom.firstChild.nextSibling, true);
452         
453        
454         var tb = new Roo.Toolbar(wdiv);
455         // add the name..
456         
457         tb.add(nm+ ":&nbsp;");
458         
459         var styles = [];
460         for(var i in this.styles) {
461             styles.push(i);
462         }
463         
464         // styles...
465         if (styles && styles.length) {
466             
467             // this needs a multi-select checkbox...
468             tb.addField( new Roo.form.ComboBox({
469                 store: new Roo.data.SimpleStore({
470                     id : 'val',
471                     fields: ['val', 'selected'],
472                     data : [] 
473                 }),
474                 name : '-roo-edit-className',
475                 attrname : 'className',
476                 displayField:'val',
477                 typeAhead: false,
478                 mode: 'local',
479                 editable : false,
480                 triggerAction: 'all',
481                 emptyText:'Select Style',
482                 selectOnFocus:true,
483                 width: 130,
484                 listeners : {
485                     'select': function(c, r, i) {
486                         // initial support only for on class per el..
487                         tb.selectedNode.className =  r ? r.get('val') : '';
488                         editor.syncValue();
489                     }
490                 }
491     
492             }));
493         }
494             
495         
496         
497         for (var i in tlist) {
498             
499             var item = tlist[i];
500             tb.add(item.title + ":&nbsp;");
501             
502             
503             
504             
505             if (item.opts) {
506                 // opts == pulldown..
507                 tb.addField( new Roo.form.ComboBox({
508                     store: new Roo.data.SimpleStore({
509                         id : 'val',
510                         fields: ['val'],
511                         data : item.opts  
512                     }),
513                     name : '-roo-edit-' + i,
514                     attrname : i,
515                     displayField:'val',
516                     typeAhead: false,
517                     mode: 'local',
518                     editable : false,
519                     triggerAction: 'all',
520                     emptyText:'Select',
521                     selectOnFocus:true,
522                     width: item.width ? item.width  : 130,
523                     listeners : {
524                         'select': function(c, r, i) {
525                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
526                         }
527                     }
528
529                 }));
530                 continue;
531                     
532                  
533                 
534                 tb.addField( new Roo.form.TextField({
535                     name: i,
536                     width: 100,
537                     //allowBlank:false,
538                     value: ''
539                 }));
540                 continue;
541             }
542             tb.addField( new Roo.form.TextField({
543                 name: '-roo-edit-' + i,
544                 attrname : i,
545                 
546                 width: item.width,
547                 //allowBlank:true,
548                 value: '',
549                 listeners: {
550                     'change' : function(f, nv, ov) {
551                         tb.selectedNode.setAttribute(f.attrname, nv);
552                     }
553                 }
554             }));
555              
556         }
557         tb.addFill();
558         var _this = this;
559         tb.addButton( {
560             text: 'Remove Tag',
561     
562             listeners : {
563                 click : function ()
564                 {
565                     // remove
566                     // undo does not work.
567                      
568                     var sn = tb.selectedNode;
569                     Roo.log(sn);
570                     var pn = sn.parentNode;
571                     
572                     var stn =  sn.childNodes[0];
573                     var en = sn.childNodes[sn.childNodes.length - 1 ];
574                     while (sn.childNodes.length) {
575                         var node = sn.childNodes[0];
576                         sn.removeChild(node);
577                         Roo.log(node);
578                         pn.insertBefore(node, sn);
579                         
580                     }
581                     pn.removeChild(sn);
582                     var range = editor.createRange();
583         
584                     range.setStart(stn,0);
585                     range.setEnd(en,0); //????
586                     //range.selectNode(sel);
587                     
588                     
589                     var selection = editor.getSelection();
590                     selection.removeAllRanges();
591                     selection.addRange(range);
592                     
593                     
594                     
595                     //_this.updateToolbar(null, null, pn);
596                     _this.updateToolbar(null, null, pn);
597                     this.footDisp.dom.innerHTML = ''; 
598                 }
599             }
600             
601                     
602                 
603             
604         });
605         
606         
607         tb.el.on('click', function(e){
608             e.preventDefault(); // what does this do?
609         });
610         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
611         tb.el.hide();
612         tb.name = nm;
613         // dont need to disable them... as they will get hidden
614         return tb;
615          
616         
617     },
618     buildFooter : function()
619     {
620         
621         var fel = this.editor.wrap.createChild();
622         this.footer = new Roo.Toolbar(fel);
623         // toolbar has scrolly on left / right?
624         var footDisp= new Roo.Toolbar.Fill();
625         var _t = this;
626         this.footer.add(
627             {
628                 text : '&lt;',
629                 xtype: 'Button',
630                 handler : function() {
631                     _t.footDisp.scrollTo('left',0,true)
632                 }
633             }
634         );
635         this.footer.add( footDisp );
636         this.footer.add( 
637             {
638                 text : '&gt;',
639                 xtype: 'Button',
640                 handler : function() {
641                     // no animation..
642                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
643                 }
644             }
645         );
646         var fel = Roo.get(footDisp.el);
647         fel.addClass('x-editor-context');
648         this.footDispWrap = fel; 
649         this.footDispWrap.overflow  = 'hidden';
650         
651         this.footDisp = fel.createChild();
652         this.footDispWrap.on('click', this.onContextClick, this)
653         
654         
655     },
656     onContextClick : function (ev,dom)
657     {
658         ev.preventDefault();
659         var  cn = dom.className;
660         Roo.log(cn);
661         if (!cn.match(/x-ed-loc-/)) {
662             return;
663         }
664         var n = cn.split('-').pop();
665         var ans = this.footerEls;
666         var sel = ans[n];
667         
668          // pick
669         var range = this.editor.createRange();
670         
671         range.selectNodeContents(sel);
672         //range.selectNode(sel);
673         
674         
675         var selection = this.editor.getSelection();
676         selection.removeAllRanges();
677         selection.addRange(range);
678         
679         
680         
681         this.updateToolbar(null, null, sel);
682         
683         
684     }
685     
686     
687     
688     
689     
690 });
691
692
693
694
695