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         [ 'helvetica,Arial,sans-serif'],
196         [ 'Courier New'],
197         [ 'Tahoma'],
198         [ 'Times New Roman,serif'],
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                         return;
378                     } 
379                    e.setValue(sel.getAttribute(e.attrname));
380                 });
381             }
382             
383             var hasStyles = false;
384             for(var i in this.styles) {
385                 hasStyles = true;
386                 break;
387             }
388             
389             // update styles
390             if (hasStyles) { 
391                 var st = this.tb.fields.item(0);
392                 
393                 st.store.removeAll();
394                
395                 
396                 var cn = sel.className.split(/\s+/);
397                 
398                 var avs = [];
399                 if (this.styles['*']) {
400                     
401                     Roo.each(this.styles['*'], function(v) {
402                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
403                     });
404                 }
405                 if (this.styles[tn]) { 
406                     Roo.each(this.styles[tn], function(v) {
407                         avs.push( [ v , cn.indexOf(v) > -1 ? 1 : 0 ] );         
408                     });
409                 }
410                 
411                 st.store.loadData(avs);
412                 st.collapse();
413                 st.setValue(cn);
414             }
415             // flag our selected Node.
416             this.tb.selectedNode = sel;
417            
418            
419             Roo.menu.MenuMgr.hideAll();
420
421         }
422         
423         if (!updateFooter) {
424             //this.footDisp.dom.innerHTML = ''; 
425             return;
426         }
427         // update the footer
428         //
429         var html = '';
430         
431         this.footerEls = ans.reverse();
432         Roo.each(this.footerEls, function(a,i) {
433             if (!a) { return; }
434             html += html.length ? ' &gt; '  :  '';
435             
436             html += '<span class="x-ed-loc-' + i + '">' + a.tagName + '</span>';
437             
438         });
439        
440         // 
441         var sz = this.footDisp.up('td').getSize();
442         this.footDisp.dom.style.width = (sz.width -10) + 'px';
443         this.footDisp.dom.style.marginLeft = '5px';
444         
445         this.footDisp.dom.style.overflow = 'hidden';
446         
447         this.footDisp.dom.innerHTML = html;
448             
449         //this.editorsyncValue();
450     },
451      
452     
453    
454        
455     // private
456     onDestroy : function(){
457         if(this.rendered){
458             
459             this.tb.items.each(function(item){
460                 if(item.menu){
461                     item.menu.removeAll();
462                     if(item.menu.el){
463                         item.menu.el.destroy();
464                     }
465                 }
466                 item.destroy();
467             });
468              
469         }
470     },
471     onFirstFocus: function() {
472         // need to do this for all the toolbars..
473         this.tb.items.each(function(item){
474            item.enable();
475         });
476     },
477     buildToolbar: function(tlist, nm)
478     {
479         var editor = this.editor;
480          // create a new element.
481         var wdiv = editor.wrap.createChild({
482                 tag: 'div'
483             }, editor.wrap.dom.firstChild.nextSibling, true);
484         
485        
486         var tb = new Roo.Toolbar(wdiv);
487         // add the name..
488         
489         tb.add(nm+ ":&nbsp;");
490         
491         var styles = [];
492         for(var i in this.styles) {
493             styles.push(i);
494         }
495         
496         // styles...
497         if (styles && styles.length) {
498             
499             // this needs a multi-select checkbox...
500             tb.addField( new Roo.form.ComboBox({
501                 store: new Roo.data.SimpleStore({
502                     id : 'val',
503                     fields: ['val', 'selected'],
504                     data : [] 
505                 }),
506                 name : '-roo-edit-className',
507                 attrname : 'className',
508                 displayField: 'val',
509                 typeAhead: false,
510                 mode: 'local',
511                 editable : false,
512                 triggerAction: 'all',
513                 emptyText:'Select Style',
514                 selectOnFocus:true,
515                 width: 130,
516                 listeners : {
517                     'select': function(c, r, i) {
518                         // initial support only for on class per el..
519                         tb.selectedNode.className =  r ? r.get('val') : '';
520                         editor.syncValue();
521                     }
522                 }
523     
524             }));
525         }
526             
527         
528         
529         for (var i in tlist) {
530             
531             var item = tlist[i];
532             tb.add(item.title + ":&nbsp;");
533             
534             
535             
536             
537             if (item.opts) {
538                 // opts == pulldown..
539                 tb.addField( new Roo.form.ComboBox({
540                     store: new Roo.data.SimpleStore({
541                         id : 'val',
542                         fields: ['val', 'display'],
543                         data : item.opts  
544                     }),
545                     name : '-roo-edit-' + i,
546                     attrname : i,
547                     stylename : item.style ? item.style : false,
548                     displayField:'val',
549                     valueField : item.valueField ? item.valueField : '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                             if (c.stylename) {
560                                 tb.selectedNode.style[c.stylename] =  r.get('val');
561                                 return;
562                             }
563                             tb.selectedNode.setAttribute(c.attrname, r.get('val'));
564                         }
565                     }
566
567                 }));
568                 continue;
569                     
570                  
571                 
572                 tb.addField( new Roo.form.TextField({
573                     name: i,
574                     width: 100,
575                     //allowBlank:false,
576                     value: ''
577                 }));
578                 continue;
579             }
580             tb.addField( new Roo.form.TextField({
581                 name: '-roo-edit-' + i,
582                 attrname : i,
583                 
584                 width: item.width,
585                 //allowBlank:true,
586                 value: '',
587                 listeners: {
588                     'change' : function(f, nv, ov) {
589                         tb.selectedNode.setAttribute(f.attrname, nv);
590                     }
591                 }
592             }));
593              
594         }
595         tb.addFill();
596         var _this = this;
597         tb.addButton( {
598             text: 'Remove Tag',
599     
600             listeners : {
601                 click : function ()
602                 {
603                     // remove
604                     // undo does not work.
605                      
606                     var sn = tb.selectedNode;
607                     
608                     var pn = sn.parentNode;
609                     
610                     var stn =  sn.childNodes[0];
611                     var en = sn.childNodes[sn.childNodes.length - 1 ];
612                     while (sn.childNodes.length) {
613                         var node = sn.childNodes[0];
614                         sn.removeChild(node);
615                         //Roo.log(node);
616                         pn.insertBefore(node, sn);
617                         
618                     }
619                     pn.removeChild(sn);
620                     var range = editor.createRange();
621         
622                     range.setStart(stn,0);
623                     range.setEnd(en,0); //????
624                     //range.selectNode(sel);
625                     
626                     
627                     var selection = editor.getSelection();
628                     selection.removeAllRanges();
629                     selection.addRange(range);
630                     
631                     
632                     
633                     //_this.updateToolbar(null, null, pn);
634                     _this.updateToolbar(null, null, null);
635                     this.footDisp.dom.innerHTML = ''; 
636                 }
637             }
638             
639                     
640                 
641             
642         });
643         
644         
645         tb.el.on('click', function(e){
646             e.preventDefault(); // what does this do?
647         });
648         tb.el.setVisibilityMode( Roo.Element.DISPLAY);
649         tb.el.hide();
650         tb.name = nm;
651         // dont need to disable them... as they will get hidden
652         return tb;
653          
654         
655     },
656     buildFooter : function()
657     {
658         
659         var fel = this.editor.wrap.createChild();
660         this.footer = new Roo.Toolbar(fel);
661         // toolbar has scrolly on left / right?
662         var footDisp= new Roo.Toolbar.Fill();
663         var _t = this;
664         this.footer.add(
665             {
666                 text : '&lt;',
667                 xtype: 'Button',
668                 handler : function() {
669                     _t.footDisp.scrollTo('left',0,true)
670                 }
671             }
672         );
673         this.footer.add( footDisp );
674         this.footer.add( 
675             {
676                 text : '&gt;',
677                 xtype: 'Button',
678                 handler : function() {
679                     // no animation..
680                     _t.footDisp.select('span').last().scrollIntoView(_t.footDisp,true);
681                 }
682             }
683         );
684         var fel = Roo.get(footDisp.el);
685         fel.addClass('x-editor-context');
686         this.footDispWrap = fel; 
687         this.footDispWrap.overflow  = 'hidden';
688         
689         this.footDisp = fel.createChild();
690         this.footDispWrap.on('click', this.onContextClick, this)
691         
692         
693     },
694     onContextClick : function (ev,dom)
695     {
696         ev.preventDefault();
697         var  cn = dom.className;
698         //Roo.log(cn);
699         if (!cn.match(/x-ed-loc-/)) {
700             return;
701         }
702         var n = cn.split('-').pop();
703         var ans = this.footerEls;
704         var sel = ans[n];
705         
706          // pick
707         var range = this.editor.createRange();
708         
709         range.selectNodeContents(sel);
710         //range.selectNode(sel);
711         
712         
713         var selection = this.editor.getSelection();
714         selection.removeAllRanges();
715         selection.addRange(range);
716         
717         
718         
719         this.updateToolbar(null, null, sel);
720         
721         
722     }
723     
724     
725     
726     
727     
728 });
729
730
731
732
733