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