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