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