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